Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Check if a Point d Lies Inside or Outside a Circle Defined by Points a, b, c in a Plane
In this articles, we implements a C++ Program to check if a point d lies inside or outside a circle defined by points a, b, c in a plane using the following equation:
s = (x-xt)^2 + (y-yt)^2 - r*r
Where equation contains the following points:
- x, y: Any point in the plane.
- xt, yt: Center of the circle.
- r: Radius of the circle.
- s: The difference between the squared distance and ( r^2 ).
If s is equal to 0, the point lies on the circle. If s is greater than 0, the point lies outside the circle, and if s is less than 0, the point lies inside the circle.
C++ program to check if a point d lies inside or outside a circle defined by Points a, b, c in a plane
In the following example, we implement a C++ program to check if a Point Lies Inside or outside a Circle:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
const int L = 0;
const int H = 20;
// Function to generate a random point within range
double randomPoint() {
return rand() % (H - L + 1) + L;
}
int main() {
// Seed the random number generator
srand(static_cast < unsigned int > (time(nullptr)));
// Define three random points on the circle
double x1 = randomPoint(), y1 = randomPoint();
double x2 = randomPoint(), y2 = randomPoint();
double x3 = randomPoint(), y3 = randomPoint();
// Calculate slopes
double a1 = (y1 - y2) / (x1 - x2);
double a2 = (y3 - y2) / (x3 - x2);
// Compute center (c1, c2) using derived formulas
double c1 = ((a1 * a2 * (y3 - y1)) + (a1 * (x2 + x3)) - (a2 * (x1 + x2))) / (2 * (a1 - a2));
double c2 = ((((x1 + x2) / 2) - c1) / (-1 * a1)) + ((y1 + y2) / 2);
// Compute radius
double r = sqrt(pow(x3 - c1, 2) + pow(y3 - c2, 2));
cout << "The points on the circle are: (" << x1 << ", " << y1 << "), (" << x2 << ", " << y2 << "), (" << x3 << ", " << y3 << ")\n";
cout << "The center of the circle is (" << c1 << ", " << c2 << ") and radius is " << r << endl;
double u = 10, v = 10; // Example test point
cout << "\nTesting point (" << u << ", " << v << ")...";
// Check position relative to the circle
double s1 = pow(u - c1, 2) + pow(v - c2, 2) - pow(r, 2);
if (s1 < 0)
cout << "\nThe point lies **inside** the circle.\n";
else if (s1 > 0)
cout << "\nThe point lies **outside** the circle.\n";
else
cout << "\nThe point lies **on** the circle.\n";
return 0;
}
The below output tells whether point d is inside or outside of circle ?
The points on the circle are: (14, 2), (4, 0), (0, 13) The center of the circle is (7.55797, -6.21014) and radius is 20.6435 Testing point (10, 10)... The point lies **inside** the circle.
Advertisements