C++程式檢查三個點是否共線


給定三個不同值的點,任務是檢查這些點是否共線。

如果點位於同一條直線上,則稱它們為共線;如果它們位於不同的直線上,則稱它們為非共線。以下是共線和非共線點的圖形。

輸入

x1 = 1, x2 = 2, x3 = 3, y1 = 1, y2 = 4, y3 = 5

輸出

no points are not collinear

輸入

x1 = 1, y1 = 1, x2 = 1, y2 = 4, x3 = 1, y3 = 5

輸出

points are collinear

下面程式中使用的方法如下

  • 輸入點為 (x1, y1), (x2, y2), (x3, y3)

  • 應用三角形面積公式 x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)

  • 檢查以下條件:

    • 如果三角形面積為 0,則列印點共線

    • 如果三角形面積不為 0,則列印點不共線

  • 列印最終結果

演算法

Start
Step 1→ declare function to check if points are collinear or not
   void check_collinear(int x1, int y1, int x2, int y2, int x3, int y3)
      declare int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)
      IF (a == 0)
         Print "yes points are collinear"
      End
      Else
         Print "no points are not collinear"
Step 2→ In main()
   Declare int x1 = 1, x2 = 2, x3 = 3, y1 = 1, y2 = 4, y3 = 5
   Call check_collinear(x1, y1, x2, y2, x3, y3)
Stop

示例

即時演示

#include <bits/stdc++.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
//check if points are collinear or not
void check_collinear(int x1, int y1, int x2, int y2, int x3, int y3){
   int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
   if (a == 0)
      cout << "yes points are collinear";
   else
      cout << "no points are not collinear";
}
int main(){
   int x1 = 1, x2 = 2, x3 = 3, y1 = 1, y2 = 4, y3 = 5;
   check_collinear(x1, y1, x2, y2, x3, y3);
   return 0;
}

輸出

如果執行以上程式碼,它將生成以下輸出:

no points are not collinear

更新於: 2020年8月13日

2K+ 次檢視

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.