使用叉积判断两条直线是否相交
两条平面直线是否相交(直线长度大于0,可以重叠)
直线为(x1,y1),(x2,y2)和(x3,y3),(x4,y4)
#include <iostream>
using namespace std;
int cj(int a1,int a2,int b1,int b2,int c1,int c2)
{
return (c1-a1)*(b2-a2)-(c2-a2)*(b1-a1);
}
int main()
{
int x1,x2,x3,x4,y1,y2,y3,y4;
while(cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4)
{
int flag=0;
if(cj(x1,y1,x2,y2,x3,y3)*cj(x1,y1,x2,y2,x4,y4)<0&&cj(x2,y2,x1,y1,x3,y3)*cj(x2,y2,x1,y1,x4,y4)<0&&cj(x3,y3,x4,y4,x1,y1)*cj(x3,y3,x4,y4,x2,y2)<0)
flag=1;
else if(cj(x1,y1,x2,y2,x3,y3)==0&&((x3>=x1&&x3<=x2)||(x3>=x2&&x3<=x1))&&cj(x1,y1,x2,y2,x4,y4)!=0)
flag=1;
else if(cj(x1,y1,x2,y2,x4,y4)==0&&((x4>=x1&&x4<=x2)||(x4>=x2&&x4<=x1))&&cj(x1,y1,x2,y2,x3,y3)!=0)
flag=1;
else if(cj(x3,y3,x4,y4,x1,y1)==0&&((x1>=x3&&x1<=x4)||(x1>=x4&&x1<=x3))&&cj(x3,y3,x4,y4,x2,y2)!=0)
flag=1;
else if(cj(x3,y3,x4,y4,x2,y2)==0&&((x2>=x3&&x2<=x4)||(x2>=x4&&x2<=x3))&&cj(x3,y3,x4,y4,x1,y1)!=0)
flag=1;
if(flag==1)
printf("yes\n");
else
printf("no\n");
}
return 0;
}