C 庫 - pow() 函式



C 庫的 pow() 函式是 double 型別,它接受引數 x 和 y,計算 x 的 y 次冪。

此函式允許程式設計師計算底數的指定次冪,而無需手動實現複雜的乘法迴圈。

語法

以下是 C 庫函式 pow() 的語法:

double pow(double x, double y)

引數

此函式僅接受兩個引數:

  • x - 這是浮點型底數。

  • y - 這是浮點型指數。

返回值

此函式返回 xy 次冪的結果。

示例 1

以下是一個基本的 C 程式,演示了 pow() 函式的用法。

#include <stdio.h>
#include <math.h>

int main () {
   printf("Value 8.0 ^ 3 = %lf\n", pow(8.0, 3));

   printf("Value 3.05 ^ 1.98 = %lf", pow(3.05, 1.98));
   
   return(0);
}

輸出

以上程式碼的輸出結果如下:

Value 8.0 ^ 3 = 512.000000
Value 3.05 ^ 1.98 = 9.097324

示例 2

在下面的程式中,我們使用 pow() 函式演示了給定底數的冪表。

#include <stdio.h>
#include <math.h>

int main() {
   double base;
   printf("Enter the base number: ");
   scanf("%lf", &base);

   printf("Powers of %.2lf:\n", base);
   for (int i = 0; i <= 10; ++i) {
       double result = pow(base, i);
       printf("%.2lf ^ %d = %.2lf\n", base, i, result);
   }

   return 0;
}

輸出

執行以上程式碼後,得到以下結果:

Enter the base number: 5
Powers of 5.00:
5.00 ^ 0 = 1.00
5.00 ^ 1 = 5.00
5.00 ^ 2 = 25.00
5.00 ^ 3 = 125.00
5.00 ^ 4 = 625.00
5.00 ^ 5 = 3125.00
5.00 ^ 6 = 15625.00
5.00 ^ 7 = 78125.00
5.00 ^ 8 = 390625.00
5.00 ^ 9 = 1953125.00
5.00 ^ 10 = 9765625.00

示例 3

在這裡,我們建立一個程式,接受使用者輸入的底數和指數,使用 pow() 函式計算結果,並顯示結果。

#include <stdio.h>
#include <math.h>

int main() {
   double base, exponent, result;
   printf("Enter the base number: ");
   scanf("%lf", &base);
   printf("Enter the exponent: ");
   scanf("%lf", &exponent);

   result = pow(base, exponent);
   printf("%.2lf ^ %.2lf = %.2lf\n", base, exponent, result);

   return 0;
}

輸出

執行程式碼後,得到以下結果:

Enter the base number: 5
Enter the exponent: 2
5.00 ^ 2.00 = 25.00

Or,

Enter the base number: 3
Enter the exponent: 3
3.00 ^ 3.00 = 27.00
廣告