您的位置:首页 > 编程语言 > C语言/C++

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

2015-09-14 16:53 399 查看
注:如果要计算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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  递归