Home > database >  how to check a point if it lies inside a rectangle
how to check a point if it lies inside a rectangle

Time:07-25

I have a rectangle Rect (x,y,w,h) and a point P (px, py). x and y are the top left coordinate of the rectangle. w is it's width. h is it's height. px and py are the coordinate of the point P. Does anyone knows the algorithm to check if P lies inside Rect. Surprisingly, I couldn't find any correct answer for my question on the internet. Much appreciate!

CodePudding user response:

The point P(px, py) lies inside the Rectangle with top left pt. coordinates (x,y) and width and height w&h respectively if both the conditions satisfy:

  • x < px < (x w)
  • y > py > (y-h)

Hope this helps :)

CodePudding user response:

It's just a metter of checking that x is within the rectangle left and right sides and that y is within top and bottom:

#include <iostream>

struct Point {
    double x, y;
};

struct Rect {
    double x, y, w, h;
    
    bool contains(const Point& p) {
        return p.x >= x && p.y >= y && p.x <= x w && p.y <= y h;
    }
};

int main() {
    Rect r({ 3,4,5,8 });
    std::cout << r.contains({ 3.2, 7.3 });
    return 0;
}

CodePudding user response:

use this piece of code:

#include <iostream>

int main()
{
  int x, y, w, h;
  std::cin >> x >> y >> w >> h;
      
  int px, py;
  std::cin >> px >> py;
  
  if(px >= x && px <= (x   w) && py <= y && py >= (y - h))
    std::cout << "point is in the rectangle";
  else
    std::cout << "point is out of the rectangle";
}
  • Related