我试图创建一个函数来检查两条有限线是否相互交叉(返回 0 或 1 )。
首先我声明这些结构
typedef struct _Point{
double x;
double y;
}point;
typedef struct _Line{
int numVertex;
point *vertex;
}line;
比,我在这里开始功能。
int lineInterceptsLine(line L1, line L2){
double b1,b2,a1,a2,xi,yi;
// First of all Im using both vertex to get each line equation in the form -> y=bx + a. And I start making an exception because if both vertex have the same value for x, b will be 0, but in the equation Ill endup dividing by 0 and will cause error.
if((L1.vertex[1].x-L1.vertex[0].x)==0){
b1 = 0; // Check line1
}else{
b1 = (L1.vertex[1].y-L1.vertex[0].y)/(L1.vertex[1].x-L1.vertex[0].x);
}
if((L2.vertex[1].x-L2.vertex[0].x)==0){
b2 = 0; // Check line 2
}else{
b2 = (L2.vertex[1].y-L2.vertex[0].y)/(L2.vertex[1].x-L2.vertex[0].x);
}
a1 = L1.vertex[0].y-b1*L1.vertex[0].x;
a2 = L2.vertex[0].y-b2*L2.vertex[0].x;
// Now I have both lines equation
if(a1==a2){
if(b1==b2){
}else{
if(((L1.vertex[0].x<0)&&(L1.vertex[1].x>0)&&(L2.vertex[0].x<0)&&(L2.vertex[1].x>0)) ||
((L1.vertex[0].x>0)&&(L1.vertex[1].x<0)&&(L2.vertex[0].x>0)&&(L2.vertex[1].x<0)) ) {
return 1;
}else{
return 0;
}
}
return 0;
}else if(b1==b2){
return 0;
}else{
xi = (b2-b1)/(a1-a2);
yi = ((a2*b1)-(a1*b2))/(a2-a1);
if(((L1.vertex[0].x-xi)*(xi-L1.vertex[1].x))>=0 &&
((L2.vertex[0].x-xi)*(xi-L2.vertex[1].x))>=0 &&
((L1.vertex[0].y-yi)*(yi-L1.vertex[1].y))>=0 &&
((L2.vertex[0].y-yi)*(yi-L2.vertex[1].y))>=0 )
{
return 1;
}
else{
return 0;
}
}
}
我不知道为什么某些测试不起作用,例如具有以下值的测试:
L1.vertex[0].x=0;
L1.vertex[0].y=1;
L1.vertex[1].x=3;
L1.vertex[1].y=1;
L2.vertex[0].x=2;
L2.vertex[0].y=2;
L2.vertex[1].x=2;
L2.vertex[1].y=0;
如果您找不到问题并知道有效的算法,那也很棒。提前致谢!