ฟังก์ชัน Power ใช้คำนวณกำลังของตัวเลขที่กำหนด
ฟังก์ชัน pow หาค่า a ยกกำลัง b คือ aᵇ
ไวยากรณ์
double pow(double a , double b)
รับค่า double เข้ามา 2 ตัว และคืนค่า double ฟังก์ชัน pow() อยู่ในแพ็กเกจ math.h
ถ้าส่ง integer เข้าไป จะแปลงเป็น double แต่บางครั้งการแปลงอาจทำให้ค่าต่ำกว่าจริง เช่น ส่ง 3 แปลงเป็น 2.99 แล้วยกกำลัง 2 ได้ 8.9994 กลายเป็น 8 ซึ่งเป็นข้อผิดพลาด แม้จะนادرة แต่เพื่อแก้ไข ให้บวก 0.25 เข้าไป
โค้ดตัวอย่าง
#include <stdio.h> #include <math.h> int main() { double x = 6.1, y = 2; double result = pow(x, y); printf("%f raised to the power of %f is %f \n" ,x,y, result ); int a = 5 , b = 2; int square = pow(a,b); printf("%d raised to the power of %d is %d \n", a,b, square ); return 0; }ผลลัพธ์
6.100000 raised to the power of 2.000000 is 37.210000 5 raised to the power of 2 is 25