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

注:如果要计算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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值