下面是一個C++中計算冪次的函數的遞歸實現方法:
#include <iostream>
double power(double base, int exponent) {
if (exponent == 0) {
return 1;
}
else if (exponent > 0) {
return base * power(base, exponent - 1);
}
else {
return 1 / base * power(base, exponent + 1);
}
}
int main() {
double base = 2;
int exponent = 3;
double result = power(base, exponent);
std::cout << base << " raised to the power of " << exponent << " is: " << result << std::endl;
return 0;
}
在這個例子中,power
函數采用了遞歸的方式計算冪次。當指數為0時,返回1;當指數大于0時,返回基數乘以power(base, exponent-1)
;當指數小于0時,返回1除以基數乘以power(base, exponent+1)
。然后在main
函數中調用power
函數來計算結果。