C++程式:應用上-下-上測試查詢點相對於直線的位置


這是一個C++程式,用於應用上-下-上測試來查詢點相對於直線的位置。對於平面上的任意點t (xt, yt),其相對於連線m和n的直線L的位置可以透過計算標量s來找到 -

Y = A xt + B yt + C

如果Y< 0,則t位於L的順時針半平面;如果Y>0,則t位於逆時針半平面;如果Y= 0,則t位於L上。

演算法

Begin
   Take the points as input.
   For generating equation of the line, generate random numbers for coefficient of x and y (x1,x2,y1,y2) by using rand function at every time of compilation.
   Compute s as (y2 - y1) * x + (x1 - x2) * y + (x2 * y1 - x1 * y2).
   if (s < 0)
      Print "The point lies below the line or left side of the line".
   else if (s >0)
      print "The point lies above the line or right side of the line";
   else
      print "The point lies on the line"
End

示例程式碼

 線上演示

#include<stdlib.h>
#include<iostream>
#include<math.h>
#include<time.h>
using namespace std;

const int L = 0;
const int H= 20;

int main(int argc, char **argv) {
   time_t seconds;
   time(&seconds);
   srand((unsigned int) seconds);

   int x1, x2, y1, y2;
   x1 = rand() % (H - L + 1) + L;
   x2 = rand() % (H - L + 1) + L;
   y1 = rand() % (H - L + 1) + L;
   y2 = rand() % (H - L + 1) + L;

   cout << "The Equation of the 1st line is : (" << (y2 - y1) << ")x+(" << (x1 - x2) << ")y+(" << (x2 * y1 - x1 * y2) << ") = 0\n";

   int x, y;
   cout << "\nEnter the point:";
   cin >>x;
   cin >>y;

   int s = (y2 - y1) * x + (x1 - x2) * y + (x2 * y1 - x1 * y2);
   if (s < 0)
      cout << "The point lies below the line or left side of the line";
   else if (s >0)
      cout << "The point lies above the line or right side of the line";
   else
      cout << "The point lies on the line";
      return 0;
}

輸出

The Equation of the 1st line is : (7)x+(0)y+(-105) = 0

Enter the point:7
6
The point lies below the line or left side of the line

更新於: 2019年7月30日

422 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.