### Checking if a point is inside a rectangle

How do you check if a point is inside a rectangle?

my upper left corner is _corner(10,10)
and my width is 10 , and height : 20;

This is my contains method.

 ``1234567891011121314`` ``````bool Rect::Contains( Point p ) { if( p.GetX() >= _corner.GetX() + _width && p.GetY() >= _corner.GetY() + _height ) { cout<<" it was not inside the rectangle"<

Is this the correct way to do it ? I'm pretty sure its not .
Well, I'd imagine the way to do it is to check if the first (x) coordinate is greater than or equal to 10 and less than or equal to 10 plus the width, AND that the height is greater than or equal to 10 and less than or equal to 10 plus the height. In your case, you have the less than or equal to part down, but you forgot to make the case when the point is, say, (1,1) or (17,2). You need another if statement to make sure both coordinates are greater than or equal to 10.
You need two tests for x and two tests for y.
For example
`( p.GetX() >= _corner.GetX() ) && ( p.GetX() <= _corner.GetX() + _width )`
Last edited on
So I just need to add what you suggested Chervil.
The code I suggested is just for the x-values. You need another similar piece of code for the y-values.
Ok thanks !!
Topic archived. No new replies allowed.