原文: https://www.programiz.com/cpp-programming/examples/power-recursion
要理解此示例,您应该了解以下 C++ 编程主题:
#include <iostream>
using namespace std;
int calculatePower(int, int);
int main()
{
int base, powerRaised, result;
cout << "Enter base number: ";
cin >> base;
cout << "Enter power number(positive integer): ";
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;
}
输出
Enter base number: 3
Enter power number(positive integer): 4
3^4 = 81
仅当指数为正整数时,此技术才能计算功效。
要查找任意数量的幂,可以使用pow()
函数。
result = pow(base, exponent);