เราจะมาดูวิธีการใช้ค่าคงที่ PI ในโปรแกรม C++ ค่าคงที่ PI มีอยู่ในไฟล์ส่วนหัว cmath ชื่อของค่าคงที่คือ M_PI เราสามารถรวมไฟล์ส่วนหัวนั้นและใช้ค่าคงที่เพื่อดำเนินการได้
ในตัวอย่างต่อไปนี้ เราจะมาดูวิธีการหาพื้นที่ของวงกลมโดยใช้ค่าคงที่ PI
โค้ดตัวอย่าง
#include <iostream>
#include <cmath>
using namespace std;
float area(int radius) {
return M_PI * (radius * radius);
}
int main () {
cout << "Area of a circle with radius 7 unit is: " << area(7);
} ผลลัพธ์
Area of a circle with radius 7 unit is: 153.938