ฟังก์ชัน pow() ใช้คำนวณค่าของฐาน (Base) ยกกำลัง (Exponent) อยู่ใน Header <math.h>
ไวยากรณ์
#include <math.h>
double pow(double base, double exponent);
base- ค่าฐาน (Base Value)exponent- ค่ากำลัง (Power Value)- คืนค่า:
baseexponentเป็น double
ตัวอย่าง
#include <stdio.h>
#include <math.h>
int main() {
double x = 5.5;
double y = 4.0;
double result;
result = pow(x, y); // 5.5^4
printf("The value : %lf\n", result);
// ตัวอย่างเพิ่มเติม
printf("2^10 = %lf\n", pow(2, 10)); // 1024.0
printf("10^3 = %lf\n", pow(10, 3)); // 1000.0
printf("2^0.5 = %lf\n", pow(2, 0.5)); // 1.414... (Square Root)
printf("(-2)^3 = %lf\n", pow(-2, 3)); // -8.0
return 0;
}
ผลลัพธ์
The value : 915.062500
2^10 = 1024.000000
10^3 = 1000.000000
2^0.5 = 1.414214
(-2)^3 = -8.000000
ปัญหาที่พบบ่อย: Linker Error
undefined reference to `pow'
error: ld returned 1 exit status
สาเหตุ
Include <math.h> แล้วแต่ ไม่ได้ Link Math Library (libm)
วิธีแก้
# GCC/Clang
gcc program.c -o program -lm
# หรือ
gcc -lm program.c -o program
-lm = Link กับ Library Math (libm.a / libm.so)
ฟังก์ชันเกี่ยวข้อง
| ฟังก์ชัน | Header | คำอธิบาย |
|---|---|---|
pow() | math.h | x^y (General Power) |
sqrt() | math.h | √x (Square Root) |
cbrt() | math.h | ∛x (Cube Root) - C99 |
exp() | math.h | e^x |
log() | math.h | ln(x) (Natural Log) |
log10() | math.h | log10(x) |
powf() | math.h | float version - C99 |
powl() | math.h | long double version - C99 |
ข้อควรระวัง
- Precision: ผลลัพธ์เป็น double อาจมี Floating Point Error (เช่น
pow(10, 2)อาจได้ 99.999999) - Domain Error:
pow(negative, non-integer)จะได้ NaN (Not a Number) และตั้งerrno = EDOM - Range Error: ผลลัพธ์ใหญ่เกินไป →
HUGE_VALและerrno = ERANGE - Integer Power: สำหรับ Integer Exponent ใช้ Loop/Multiplication เร็วกว่าและแม่นยำกว่า
Integer Power Function (แม่นยำและเร็วกว่า)
long long int_pow(int base, int exp) {
long long result = 1;
while (exp > 0) {
if (exp & 1) result *= base;
base *= base;
exp >>= 1;
}
return result;
}