C++程式:求過兩點直線


在這個問題中,我們給定座標平面上的兩點 A 和 B 的座標。我們的任務是建立一個 C++ 程式來求過這兩點的直線。

問題描述

為了求出直線,我們需要使用直線方程,並利用座標來求解。

讓我們舉個例子來理解這個問題

輸入:A = (3, 3) B = (6, 1) 

輸出:2x + 3y = 15

解決方案

為了求出直線方程,我們將使用直線的一般方程−

ax + by = c

這個方程必須同時滿足點 A(x1, y1) 和 B(x2, y2) 的座標。

這將得到以下方程:

ax1 + by1 = c

ax2 + by2 = c

現在,由於 c 對兩個方程都是相同的,所以我們有

ax1 + by1 = ax2 + by2

=> ax1 - ax2 = by2 - by1

化簡得到:

$$a = (y2 - y1)$$ $$b = (x1 - x2)$$

c 可以透過以下方程求得:

$$ax1 + by1 = c$$

所以,直線方程為:

$$a = (y2 - y1)$$ $$b = (x1 - x2)$$ $$c = ax1 + by1$$

示例

 線上演示

#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;
}

輸出

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

更新於: 2020年10月9日

764 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.