บทนำ
โจทย์: กำหนดวงกลมหนึ่งวง (พิกัดศูนย์กลางและรัศมี) และจุดหนึ่งจุด ต้องการทราบว่าจุดนั้นอยู่ภายในวงกลมหรือไม่
วิธีแก้ปัญหา
คำนวณระยะห่างจากจุดที่กำหนดไปยังศูนย์กลางวงกลม หากระยะห่างน้อยกว่าหรือเท่ากับรัศมี จุดนั้นอยู่ภายในวงกลม มิฉะนั้นอยู่นอกวงกลม
สูตรระยะห่างยกกำลังสอง: dist = (x - cx)² + (y - cy)²
เงื่อนไข: dist <= r² → อยู่ภายในวงกลม
ตัวอย่างโค้ด C++
#include <iostream>
#include <cmath>
using namespace std;
bool isInsideCircle(int cx, int cy, int r, int x, int y) {
int dist = (x - cx) * (x - cx) + (y - cy) * (y - cy);
if (dist <= r * r)
return true;
else
return false;
}
int main() {
int x = 4, y = 4, cx = 1, cy = 1, rad = 6;
if (isInsideCircle(cx, cy, rad, x, y)) {
cout << "Inside Circle";
} else {
cout << "Outside Circle";
}
return 0;
}
ผลลัพธ์
Inside Circle