💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# C++ 程序:使用递归计算幂 > 原文: [https://www.programiz.com/cpp-programming/examples/power-recursion](https://www.programiz.com/cpp-programming/examples/power-recursion) #### 该程序使用递归来计算数字的幂,其中用户输入了底数和指数。 要理解此示例,您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题: * [C++ 函数](/cpp-programming/function) * [C++ 中用户定义函数的类型](/cpp-programming/user-defined-function-types) * [C++ 递归](/cpp-programming/recursion) * * * * * * ## 示例:使用递归编程 ```cpp #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; } ``` **输出** ```cpp Enter base number: 3 Enter power number(positive integer): 4 3^4 = 81 ``` 仅当指数为正整数时,此技术才能计算功效。 要查找任意数量的幂,可以使用`pow()`函数。 ```cpp result = pow(base, exponent); ```