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

หาสมการเส้นตรงที่ผ่าน 2 จุดใน C++

กำหนดจุด A(x1,y1) และ B(x2,y2) หาสมการเส้นตรงที่ผ่านทั้งสองจุดในรูปแบบ ax + by = c

ตัวอย่าง: A(3,3), B(6,1) → 2x + 3y = 15

วิธีแก้ปัญหา (Analytic Geometry)

จากสมการ ax + by = c ที่ทั้งสองจุดต้องทำให้เป็นจริง:

  • ax1 + by1 = c
  • ax2 + by2 = c

เทียบ c ทั้งสองข้าง: a(x1-x2) = b(y2-y1)

ได้: a = y2 - y1, b = x1 - x2, c = ax1 + by1

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

#include <iostream>
using namespace std;

void findLine(int points[2][2]) {
    int a = points[1][1] - points[0][1];
    int b = points[0][0] - points[1][0];
    int c = a * points[0][0] + b * points[0][1];
    cout << "(" << a << "x) + (" << b << "y) = (" << c << ")";
}

int main() {
    int points[2][2] = {{5, 9}, {1, 4}};
    cout << "The equation of line is ";
    findLine(points);
    return 0;
}

Output

The equation of line is (-5x) + (4y) = (11)