For the determination of whether two straight lines intersect, use the cross product:
For example, two straight lines, p1 p2, q1q2, are used to judge whether they intersect, then according to q1p1 cross q1q2*q1q2 cross q2p2 If it is greater than or equal to 0, it will intersect, otherwise it will not intersect.
Here is the judgment code:
#include<stdio.h>
typedef
struct
node{
int
x,y;
}point;
point p1,p2,q1,q2;
int
result1,result2;
int
cross(point a,point b1,point b2)
{
int
x1,y1,x2,y2;
x1=a.x-b1.x;
y1=a.y-b1.y;
x2=b2.x-b1.x;
y2=b2.y-b1.y;
return
x1*y2-x2*y1;
}
int
main()
{
while
(1)
{
scanf(
"%d %d"
,&p1.x,&p1.y);
scanf(
"%d %d"
,&p2.x,&p2.y);
scanf(
"%d %d"
,&q1.x,&q1.y);
scanf(
"%d %d"
,&q2.x,&q2.y);
result1=cross(p1,q1,q2); 注意cross中向量的顺序,要相减的向量放在前面;
result2=cross(p2,q2,q1);
printf(
"result1=%d result2=%d\n"
,result1,result2);
if
(result1*result2>=0)printf(
"YES\n"
);
// 叉乘后两向量的乘积大于0则相交
else
printf(
"NO\n"
);
// 反之则不相交。
}
}
|