我试图理解为什么我的代码用于确定给定的点是否在(包括边框)内还是没有矩形。目前我收到的是0,无论该点是否存在或者是否存在,并且我发现难以诊断这一点。我在哪里打个嗝?
#include <stdio.h>
int InRectangle( float pt[2], float rect[4] )
{
float x=pt[0];
float y=pt[1];
float box_x=rect[0];
float box_y=rect[1];
float box_x_opp=rect[2];
float box_y_opp=rect[3];
float x_diff=0;
float y_diff=0;
x_diff = box_x_opp - box_x ;
y_diff = box_y_opp - box_y;
//if x_diff is + and y diff is +
if (x_diff>=0 && y_diff>=0)
{
if ((x >= box_x) && (x <= box_x_opp) && (y>=box_y) && (y<=box_y_opp))
{return 1;}
}
//if x_diff is - and y diff is -
if (x_diff<0 && y_diff<0)
{
if ((x <= box_x) && (x >= box_x_opp) && (y>=box_y) && (y<=box_y_opp))
{return 1;}
}
//if x_diff is + and y diff is -
if (x_diff>=0 && y_diff<0)
{
if ((x >= box_x) && (x <= box_x_opp) && (y<=box_y) && (y>=box_y_opp))
{return 1;}
}
//if x_diff is - and y diff is +
if (x_diff<0 && y_diff>=0)
{
if ((x <= box_x) && (x >= box_x_opp) && (y>=box_y) && (y<=box_y_opp))
{return 1;}
}
else
{return 0;}
}
答案 0 :(得分:2)
似乎大规模过于复杂,这就是为什么很难找到错误!
您需要的只是:
return x > rect_minx_x && x < rect_max_x && y > rect_min_y && y < rect_max_y;
当然,您需要弄清楚所有这些值,但这很简单。
答案 1 :(得分:0)
另外:如果是这样的话,你忘了在第二点翻转y点检查:
//if x_diff is - and y diff is -
if (x_diff<0 && y_diff<0)
{
if ((x <= box_x) && (x >= box_x_opp) && (y>=box_y) && (y<=box_y_opp))
{return 1;}
}
应该是:
//if x_diff is - and y diff is -
if (x_diff<0 && y_diff<0)
{
if ((x <= box_x) && (x >= box_x_opp) && (y <= box_y) && (y >= box_y_opp))
{return 1;}
}
因为在这种情况下box_x
大于或等于box_x_opp
且box_y
大于或等于box_y_opp
让您的代码更具可读性,例如
float xMin, xMax, yMin, yMax;
if (rect[0] >= rect[2]) {
xMin = rect[2];
xMax = rect[0];
} else {
xMin = rect[0];
xMax = rect[2];
}
if (rect[1] >= rect[3]) {
yMin = rect[3];
yMax = rect[1];
} else {
yMin = rect[1];
yMax = rect[3];
}
然后你可以将它与solution by John3136结合起来解决:
return x >= xMin && x <= xMax && y >= yMin && y <= yMax;