C++程式:判斷平面內由點a、b、c定義的圓內或圓外一點d


我們將考慮一個C++程式,利用方程來檢查點d是否位於由平面上的點a、b、c定義的圓內或圓外。

s = (x-xt)^2 + (y-yt)^2 – r*r

其中,對於平面上的任意一點t(xt, yt),其相對於由3個點(x1, y1)、(x2, y2)、(x3, y3)定義的圓的位置。

如果s < 0,則t位於圓內。

如果s > 0,則t位於圓外。

如果s = 0,則t位於圓上。

演算法

Begin
   Take the points at input.
   Declare constant L = 0 and H = 20
   Declare the variables of the equation.
   For generating equation, generate random numbers for coefficient of x and y by using rand at every time of compilation.
   Calculate the center of the circle.
   Calculate the radius of the circle.
   Calculate s.
   if s < 0, print point lies inside the circle.
      else if s >0, print point lies outside the circle.
         else if s = 0, print point lies on the circle.
End

示例程式碼

 線上演示

#include<time.h>
#include<stdlib.h>
#include<iostream>
#include<math.h>

using namespace std;
const int L= 0;
const int H = 20;

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

   double x1, x2, y1, y2, x3, y3;
   double a1, a2, c1, c2, r;
   x1 = rand() % (H - L+ 1) + L;
   x2 = rand() % (H - L + 1) + L;
   x3 = rand() % (H- L + 1) + L;
   y1 = rand() % (H- L + 1) + L;
   y2 = rand() % (H- L+ 1) + L;
   y3 = rand() % (H- L + 1) + L;
   a1 = (y1 - y2) / (x1 - x2);
   a2 = (y3 - y2) / (x3 - x2);

   c1 = ((a1 * a2 * (y3 - y1)) + (a1 * (x2 + x3)) - (a2 * (x1 + x2))) / (2 * (a1 - a2));//calculate center of circle
   c2 = ((((x1 + x2) / 2) - c1) / (-1 * a1)) + ((y1 + y2) / 2);//calculate center of circle
   r = sqrt(((x3 - c1) * (x3 - c1)) + ((y3 - c2) * (y3 - c2)));//calcultate radius
   cout << "The points on the circle are: (" << x1 << ", " << y1 << "), (" << x2 << ", " << y2 << "), (" << x3 << ", " << y3 << ")";
   cout << "\nThe center of the circle is (" << c1 << ", " << c2 << ") and radius is " << r;

   cout << "\nEnter the point : ";
   int u, v;
   cin >>u;
   cin >>v;

   double s1 = ((u - c1) * (u - c1)) + ((v - c2) * (v - c1)) - (r * r);
   if (s1 < 0)
      cout << "\nThe point lies inside the circle";
   else if (s1 >0)
      cout << "\nThe point lies outside the circle";
   else
      cout << "\nThe point lies on the circle";
      return 0;
}

輸出

The points on the circle are: (8, 4), (9, 17), (5, 9)
The center of the circle is (12.6364, 10.8182) and radius is 7.84983
Enter the point : 7
6

The point lies outside the circle

更新於:2019年7月30日

221 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告