使用遞迴計算冪的 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