判断两直线p1p2与q1q2是否相交,用向量叉积来判断
如果P x Q >0,则P在Q的顺时针方向;
如果P x Q <0,则P在Q的逆时针方向;
如果P x Q=0,则P与Q共线,可能同向也可能反向
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <iostream> typedef struct node { double x,y; }point; point p1,p2,q1,q2; double result1,result2; double crossProduct(point a,point b1,point b2) { double 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("%lf%lf",&p1.x,&p1.y); scanf("%lf%lf",&p2.x,&p2.y); scanf("%lf%lf",&q1.x,&q1.y); scanf("%lf%lf",&q2.x,&q2.y); result1=crossProduct(p1,q1,q2);//注意向量顺序 result2=crossProduct(p2,q2,q1); printf("%lf %lf\n",result1,result2); if(result1*result2>=0)printf("YES\n");//如果叉乘大于0则相交 else printf("NO\n"); } return 0; }
转自:http://www.cnblogs.com/ysh-blog/archive/2012/07/10/2583905.html