使用递归计算幂的 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,因为任何数的零次方都为 1。如果幂不为零,则函数递归地调用自身。以下代码片段演示了这一点。
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP