简体   繁体   中英

how to check a point if it lies inside a rectangle

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!

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 > (yh)

Hope this helps :)

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;
}

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM