编程:判断一个点是否在矩形内部
作者:互联网
题目描述:
在二维坐标系中,所有的值是double类型,那么一个矩形可以由四个点来代表,(x1, y1)为最左的点,(x2, y2)为最上的点,(x3, y3)为最下的点,(x4, y4)为最右的点。
给定4个点代表的矩形,再给定一个点(x, y),判断(x, y)是否在矩形中
题目分析:
- 矩形的边平行于坐标轴
此时(x1, y1)为左上角的点,(x2, y2)为右上角的点,(x3, y3)为左下角的点,(x4, y4)为右下角的点。这种情况很好判断。
- 矩形的边不平行于坐标轴
此时,需要旋转矩形,使之平行于坐标轴。
#include<iostream>
#include<cmath>
using namespace std;
bool isInside(double x1, double x4, double y1, double y4, double x, double y)
{
if(x <= x1) return false;
if(x >= x4) return false;
if(y >= y1) return false;
if(y <= y4) return false;
return true;
}
bool isInside(double x1, double y1, double x2, double y2, double x3, double y3,
double x4, double y4, double x, double y)
{
if(x1 == x3) return isInside(x1, x4, y1, y4, x, y);
double l = y4 - y3;
double k = x4 - x3;
double s = sqrt(k * k + l * l);
double sin = l / s;
double cos = k / s;
double x1r = cos * x1 + sin * y1;
double y1r = -x1 * sin + y1 * cos;
double x4r = cos * x4 + sin * y4;
double y4r = -x4 * sin + y4 * cos;
double xr = cos * x + sin * y;
double yr = -x * sin + y * cos;
return isInside(x1r, x4r, y1r, y4r, xr, yr);
}
int main()
{
double x1, y1, x2, y2, x3, y3, x4, y4, x, y;
cin >> x1 >> y1;
cin >> x2 >> y2;
cin >> x3 >> y3;
cin >> x4 >> y4;
cin >> x >> y;
if(isInside(x1, y1, x2, y2, x3, y3, x4, y4, x, y))
{
cout << "Yes" << endl;
}
else
{
cout << "No" <<endl;
}
return 0;
}
标签:x1,一个点,double,编程,y1,矩形,y4,x4 来源: https://www.cnblogs.com/xiaobaizzz/p/12227288.html