Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C 語言冪函數 pow:用法、範例與連結陷阱

要算 x 的 y 次方,C 語言沒有 ** 這種運算子,得靠標準函式庫 math.h 裡的 pow。

函式原型:double pow(double x, double y);
功能:回傳 x 的 y 次方。
標頭檔:<math.h>

基本範例

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

int main(void)
{
    double x = 2.0, y = 3.0;

    printf("%lf raised to %lf is %lf\n", x, y, pow(x, y));
    return 0;
}

輸出為 2.000000 raised to 3.000000 is 8.000000。

兩個實務上會踩到的坑

連結時找不到符號。在 Linux 上用 gcc 編譯時,若只寫 gcc demo.c,會出現 undefined reference to pow 這類錯誤。原因是數學函式庫需要明確連結,正確指令是 gcc demo.c -lm,-lm 就是 link math library。

型別是浮點。pow 收發的都是 double,因此 pow(2, 3) 的結果是 8.000000 而非整數 8,直接指定給 int 會有隱式轉型的風險。若只是求整數次方,自行用迴圈相乘通常更快也更精確;若底數與指數都是整數且結果在範圍內,也別忘了浮點運算本身有精度限制。

另外,pow 遇到定义域錯誤(例如負數的零次方以外的分數次方)會回傳 NaN 並設定 errno,需要更嚴謹的錯誤處理時,可以搭配 errno 或 C99 的 math_errhandling 一併檢查。

Copyright © Linux教程網 All Rights Reserved