使用 C++ 編寫冪(pow)函式


冪函式用於求得兩個數字的冪,即底數和指數。結果為底數乘以指數的次方。

演示這一點的一個示例如下 −

Base = 2
Exponent = 5

2^5 = 32

Hence, 2 raised to the power 5 is 32.

一個在 C++ 中演示冪函式的程式如下 −

示例

 演示

#include
using namespace std;

int main(){
   int x, y, ans = 1;

   cout << "Enter the base value: \n";
   cin >> x;

   cout << "Enter the exponent value: \n";
   cin >> y;

   for(int i=0; i<y; i++)
   ans *= x;

   cout << x <<" raised to the power "<< y <<" is "<&;lt;ans;

   return 0;
}

示例

上述程式的輸出如下 −

Enter the base value: 3
Enter the exponent value: 4
3 raised to the power 4 is 81

現在讓我們來了解一下上述程式。

底數和指數的值從使用者那裡獲取。顯示此過程的程式碼片段如下 −

cout << "Enter the base value: \n";
cin >> x;

cout << "Enter the exponent value: \n";
cin >> y;

冪的計算使用一直執行至指數值的 for 迴圈來進行。在每次透過中,底數被乘以 ans 的值。for 迴圈完成後,冪的最終值儲存在 ans 變數中。顯示此過程的程式碼片段如下 −

for(int i=0; i<y; i++)
ans *= x;

最後,顯示冪的值。顯示此過程的程式碼片段如下 −

cout << x <<" raised to the power "<< y <<" is "<<ans;

更新日期:2020 年 6 月 26 日

1K+ 次觀看

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.