[英]If point is inside a triangle (help when point is on the boundary of triangle)
下面的代码测试一个点是否在三角形内,它做的一切都是正确的,但是每当我在三角形边界上指定一个点时,它就会说它在外面(我希望它在里面)。 谁能弄清楚出了什么问题? (我没有写下面的代码,所以请我理解这种风格很可怕忽略它......相信我在我清理之前情况更糟)。
假设我输入了顶点 A(0,0) B(10,0) C(0,10) 和点 (5,0) 的三角形,它仍然会显示在三角形之外!
#include <stdio.h>
int test2( double px, double py, double m, double b ) {
if (py < m * px + b ) {
return -1; // point is under line
}else if ( py == m * px + b ){
return 0; // point is on line
} else {
return 1; // point is over line
}
}
int test1(double px, double py, double m,double b, double lx,double ly) {
return (test2(px,py, m,b) == test2(lx,ly,m,b));
}
int tritest (double x0,double y0,double x1,double y1,double x2,double y2,double px, double py) {
int line1, line2, line3;
double m01 = (y1-y0)/(x1-x0);
double b01 = m01 * -x1 + y1;
double m02, m12, b02, b12;
m02 = (y2-y0)/(x2-x0);
m12 = (y2-y1)/(x2-x1);
b02 = m02 * -x2 + y2;
b12 = m12 * -x2 + y2;
// vertical line checks
if( x1 == x0 ) {
line1 = ( (px <= x0) == (x2 <= x0) );
} else {
line1 = test1( px, py, m01, b01,x2,y2);
}
if( x1 == x2 ) {
line2 = ( (px <= x2) == (x0 <= x2) );
} else {
line2 = test1(px,py, m12, b12,x0,y0);
}
if( x2 == x0 ) {
line3 = ( (px <= x0 ) == (x1 <= x0) );} else {
line3 = test1(px, py, m02,b02,x1,y1);
}
return line1 && line2 && line3;
}
int main(int argc, char* argv[]) {
double x0,y0,x1,y1,x2,y2,px;
double py;
int scanfsReturnValueAggregatedOverAllScanfs = 0;
// get input
printf("Triangle Vertex A (enter x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &x0,&y0);
printf("\nTriangle Vertex B (enter x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &x1,&y1);
printf("\nTriangle Vertex C (enter x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &x2,&y2);
printf("\nTest Point (enter x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &px,&py);
// print error
if( scanfsReturnValueAggregatedOverAllScanfs != 8 ) {
printf("You're stup** and didn't put in the right inputs!\n");
return 1;
}
// print answer
printf("\nThe point is ");
if (tritest(x0,y0,x1,y1,x2,y2,px,py)) {
printf("INSIDE");
} else {
printf("OUTSIDE");
}
printf(" the Triangle\n");
// return 0
return 0;
}
对我来说立即出现的一件事是您正在使用==
比较双打。这种比较永远不会准确,并且可能会产生令人惊讶的结果。 最好做类似fabs(d1-d2) < 1e-3
事情来比较双打是否相等。
int test2( double px, double py, double m, double b ) {
if (py < m * px + b ) {
return -1;
}else if ( py == m * px + b ){
return 0; //Should be return 1 as point is on line.Thus inside the triangle
} else {
return 1; //should be return 0 as point is outside this line
}
}
我认为您在上述方法中返回的返回值存在问题。对于具有不同斜率的线,这些条件会有所不同。这些检查仅对 m>0 和 m<1 有效。并且您的代码运行良好,因为侥幸。测试您的代码是否有不同斜率的线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.