用 C++ 編寫一個程式來計算 pow(x,n)


在這個問題中,給定兩個整數 x 和 n。我們的任務是編寫一個程式來計算 pow(x,n)。

我們舉個例子來理解這個問題。

輸入

x = 5 , n = 3

輸出

125

計算 pow(x,n) 的程式如下,

示例

 線上演示

#include <iostream>
using namespace std;
float myPow(float x, int y) {
   if(y == 0)
      return 1;
   float temp = myPow(x, y / 2);
   if (y % 2 == 0)
      return temp*temp;
   else {
      if(y > 0)
         return x*temp*temp;
      else
         return (temp*temp)/x;
   }
}
int main() {
   float x = 5;
   int n = 7;
   cout<<x<<" raised to the power "<<n<<" is "<<myPow(x, n);
   return 0;
}

輸出

5 raised to the power 7 is 78125

該程式透過將指數分成兩半,然後乘以兩個一半,並考慮到負值,展示了一種有效的方法。

更新於: 2020-04-20

311 次瀏覽

開啟你的職業

完成課程認證

開始
廣告