C++ 程式檢查給定的一組三個點是否在同一條直線上


這是一個 C++ 程式,用於檢查給定的一組三個點是否在同一條直線上。如果這三個點形成的三角形的面積等於零,則這三個點在同一條直線上。

三角形的面積為 −

0.5 * (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)).

演算法

Begin
   Generate the points randomly.
   Calculate the area by using above formula.
   If area > 0
      Then the points don't lie on the straight line.
   else if area < 0
      Then the points don't lie on the straight line.
   else
      The points lie on the straight line.
End

示例

#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
static int L = 1;
static int U= 20;
int main(int argc, char **argv) {
   int x3, y3, x1, x2, y1, y2;
   time_t seconds;
   time(&seconds);
   srand((unsigned int) seconds);
   //Generate the points randomly using rand().
   x1 = rand() % ( U- L+ 1) + L;
   y1 = rand() % (U - L+ 1) + L;
   x2 = rand() % (U - L + 1) + L;
   y2 = rand() % (U - L+ 1) + L;
   x3 = rand() % (U - L+ 1) + L;
   y3 = rand() % (U - L+ 1) + L;
   cout << "The points are: (" << x1 << ", " << y1 << "), (" << x2 << ", " << y2 << "), & (" << x3 << ", " << y3 << ")\n";
   //calculate area
   float a = 0.5 *(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
   if (a < 0)
      cout << "The points don't lie on the straight line";
   else if (a > 0)
      cout << "The points don't lie on the straight line ";
   else
      cout << "The points lie on the straight line";
}

輸出

The points are: (20, 9), (6, 13), & (13, 11)
The points lie on the straight line

The points are: (9, 15), (4, 15), & (11, 16)
The points don't lie on the straight line

更新於:2019 年 7 月 30 日

669 次瀏覽

開啟你的 職業生涯

完成該課程以獲得認證

開始
廣告
© . All rights reserved.