注:如果要计算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;
}