C ++程序使用递归计算功效
数字的幂可以计算为x ^ y,其中x是数字,y是幂。
例如。
Let’s say, x = 2 and y = 10x^y =1024
Here, x^y is 2^10
使用递归查找功效的程序如下。
示例
#include <iostream>using namespace std;
int FindPower(int base, int power) {
if (power == 0)
return 1;
else
return (base * FindPower(base, power-1));
}
int main() {
int base = 3, power = 5;
cout<<base<<" raised to the power "<<power<<" is "<<FindPower(base, power);
return 0;
}
输出结果
3 raised to the power 5 is 243
在上面的程序中,该函数findPower()
是递归函数。如果幂为零,则该函数返回1,因为任何幂为0的数字都是1。如果幂不为0,则该函数递归调用自身。使用以下代码段对此进行了演示。
int FindPower(int base, int power) {if (power == 0)
return 1;
else
return (base * findPower(base, power-1));
}
在main()
函数中,findPower()
函数最初被调用,并显示数字的幂。
可以在下面的代码片段中看到。
3 raised to the power 5 is 243
以上是 C ++程序使用递归计算功效 的全部内容, 来源链接: utcz.com/z/316208.html