C ++程序使用递归计算功效
数字的幂可以计算为x^y,其中x是数字,y是幂。
例如。
Let’s say, x = 2 and y = 10 x^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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短