How to calculate if a point is within a circle
I am given a constructor:
Circle::Circle(const Point& c, float r) {
x_ = c.getX();
y_ = c.getY();
r_ = r;
}
All values have been initialised as shown. In the parameter I have Point&
- This just allows me to get the x and y coords using a function from a different class. Also, I have "r" which will take in the radius value.
Using this I want to check whether that: If o is a circle, it returns true if and only if p is on the inside or the boundary of the circle
For example,
I am given: Point p(1,2);
& Circle c(p,3);
I want to check if Point(3.9,2)
is on the inside or on the boundary of Circle c(p,3);
For extra reference, I will provide the Point Constructor
:
Point::Point(float x, float y) {
x_ = x;
y_ = y;
}
Initialised constructor to allow me to create getter and setters for use in other classes.
In my function I have tried this :
bool Circle::contains(const Point& p) const {
bool results;
if( ( (getX()-p.getX() ) * ( getX()-p.getX() ) ) + ( ( (getY()-p.getY() ) * ( getY()-p.getY() ) ) <= (getR()*getR())))
{
results = true;
}
else {results = false;}
return results;
}
This did not work.
Test Case I am given:
Point p(1,2);
Circle c(p,3);
if (!c.contains(p)) errorOut_("c does not contain p?",1);
if (!c.contains(Point(3.9,2))) errorOut_("c does not contain (3.9,2)?",1);
if (!c.contains(Point(3.1,4.1))) errorOut_("c does not contain (3.1,4.1)?",1);
if (!c.contains(Point(-1.1,4.1))) errorOut_("c does not contain (-1.1,4.1)?",1);
if (!c.contains(Point(-1.1,-0.1))) errorOut_("c does not contain (-1.1,-0.1)?",1);
if (!c.contains(Point(3.1,-0.1))) errorOut_("c does not contain (3.1,-0.1)?",1);
if (c.contains(Point(3.2,4.2))) errorOut_("c contains (3.2,4.2)?",1);
if (c.contains(Point(-1.2,4.2))) errorOut_("c contains (-1.2,4.2)?",1);
if (c.contains(Point(-1.2,-0.2))) errorOut_("c contains (-1.2,-0.2)?",1);
if (c.contains(Point(3.2,-0.2))) errorOut_("c contains (3.2,-0.2)?",1);
The result:
fail1: c contains (-1.2,4.2)?
fail1: c contains (-1.2,-0.2)?
fail1: c contains (3.2,-0.2)?
To check whether point lies inside circle, you need to implement this formula (strict <
if you don't need points at circumerence):
(px-cx)*(px-cx) + (py-cy)*(py-cy) <= r*r
Squared distance from point to center should be less than squared radius (to avoid sqrt calculation)
For your example
(3.9-1)^2+(2-2)^2 = 8.41 < 3*3=9 - inside
Corrected your function:
bool Circle::contains(const Point& p) const {
return ( ( (getX()-p.getX() ) * ( getX()-p.getX() ) ) +
( ( (getY()-p.getY() ) * ( getY()-p.getY() ) ) <= (getR()*getR())))
}