C++ 编写使用递归计算幂的程序
为了理解这个示例,你应该具备以下 C++ 编程 主题的知识:
示例:使用递归计算幂的程序
#include <iostream>
using namespace std;
int calculatePower(int, int);
int main()
{
int base, powerRaised, result;
cout << "输入基数:";
cin >> base;
cout << "输入指数(正整数):";
cin >> powerRaised;
result = calculatePower(base, powerRaised);
cout << base << "^" << powerRaised << " = " << result;
return 0;
}
int calculatePower(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
输出
输入基数:3
输入指数(正整数):4
3^4 = 81
这种技术只能计算指数为正整数的幂。
要计算任何数字的幂,你可以使用 pow()
函数。
result = pow(base, exponent);