กำหนดวงกลมศูนย์กลาง (h,k) รัศมี r และเส้นตรง ax + by + c = 0 ตรวจสอบความสัมพันธ์
หลักการ
ระยะห่างจากศูนย์กลางถึงเส้นตรง (Perpendicular Distance):
d = |ah + bk + c| / √(a² + b²)
- d > r → เส้นอยู่นอกวงกลม (Outside)
- d = r → เส้นสัมผัสวงกลม (Tangent/Touching)
- d < r → เส้นตัดวงกลม (Intersecting/Secant)
ตัวอย่างโค้ด
#include <iostream>
#include <cmath>
using namespace std;
void checkLineCircle(int a, int b, int c, int h, int k, int r) {
double dist = abs(a * h + b * k + c) / sqrt(a*a + b*b);
if (abs(dist - r) < 1e-9)
cout << "Touching the circle";
else if (dist < r)
cout << "Intersecting the circle";
else
cout << "Outside the circle";
}
int main() {
int r = 5, h = 0, k = 0;
int a = 3, b = 4, c = 25; // 3x + 4y + 25 = 0
checkLineCircle(a, b, c, h, k, r);
return 0;
}
ผลลัพธ์
Touching the circle
การตรวจสอบ
d = |3×0 + 4×0 + 25| / √(9+16) = 25/5 = 5 = r → Tangent ✓
ข้อควรระวัง
- ใช้
doubleสำหรับระยะทาง ป้องกัน Integer Division - เปรียบเทียบ Floating Point ด้วย Epsilon (1e-9)
- กรณี a=b=0 ไม่เป็นเส้นตรง ต้อง Validate Input
ขยาย: หาจุดตัด
แก้ระบบสมการวงกลมและเส้นตรง จะได้ 0, 1 (Tangent), หรือ 2 จุด (Secant)