Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หา Quadrant ของ Coordinate เทียบกับ Circle ใน C++

เรามี Circle หนึ่งวง (มีจุดศูนย์กลางและรัศมี) ต้องการหา Quadrant ของจุด (x, y) อีกจุดหนึ่ง เทียบกับจุดศูนย์กลางของ Circle หากจุดอยู่ภายใน Circle ให้พิมพ์ Quadrant มิฉะนั้นพิมพ์ Error ว่าจุดอยู่นอก Circle

สมมติจุดศูนย์กลาง Circle คือ (h, k) จุดที่ต้องการคือ (x, y) สมการของ Circle คือ:

(x-h)² + (y-k)² + r² = 0

มีเงื่อนไขดังนี้:

  • ถ้า (x-h)² + (y-k)² > r จุดอยู่นอก Circle
  • ถ้า (x-h)² + (y-k)² = 0 จุดอยู่บน Circle
  • ถ้า (x-h)² + (y-k)² < r จุดอยู่ใน Circle

ตัวอย่างโค้ด C++

#include <iostream>
#include <cmath>
using namespace std;

int getQuadrant(int h, int k, int rad, int x, int y) {
    if (x == h && y == k)
        return 0;
    int val = pow((x - h), 2) + pow((y - k), 2);
    if (val > pow(rad, 2))
        return -1;
    if (x > h && y >= k)
        return 1;
    if (x <= h && y > k)
        return 2;
    if (x < h && y <= k)
        return 3;
    if (x >= h && y < k)
        return 4;
}

int main() {
    int h = 0, k = 3;
    int rad = 2;
    int x = 1, y = 4;
    int ans = getQuadrant(h, k, rad, x, y);
    if (ans == -1)
        cout << "Point is Outside of the circle" << endl;
    else if (ans == 0)
        cout << "Present at the center" << endl;
    else
        cout << ans << " Quadrant" << endl;
}

ผลลัพธ์

1 Quadrant