C++ <递归求一个数的N次方(仅限一个数的正数次方)>

C++ 专栏收录该内容
51 篇文章 0 订阅

注:如果要计算double类型的数据,只需将int改为double即可,如果只是计算整数值的N次方不建议用double类型,
因为double类型只能存储一个数的近似值,所以计算的结果部分时候会有误差。

运行结果:

Enter a number to the power of another such as (x n):  2 0
The number 2 power of 0 is: 1

Enter a number to the power of another such as (x n):  2 1
The number 2 power of 1 is: 2

Enter a number to the power of another such as (x n):  2 4
The number 2 power of 4 is: 16

power.cpp

#include <iostream>

using namespace std;

long powerN(int x, int n);

int main() {
    int x, n;
    cout << "Enter a number to the power of another such as (x n):  ";
    cin >> x >> n;

    long xn = powerN(x, n);
    cout << "The number " <<  x << " power of is: " << xn << '\n';

    return 0;
}

long powerN(int x, int n) {
    long product = 1;

    if (n > 0)
        product = x * powerN(x, --n);

    return product;
}
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值