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 生日广州男生祝福语简短