标签:
题意:给两条直线,判断相交,重合或者平行
思路:判断重合可以用叉积,平行用斜率,其他情况即为相交。
求交点:
这里也用到叉积的原理。假设交点为p0(x0,y0)。则有:
(p1-p0)X(p2-p0)=0
(p3-p0)X(p2-p0)=0
展开后即是
(y1-y2)x0+(x2-x1)y0+x1y2-x2y1=0
(y3-y4)x0+(x4-x3)y0+x3y4-x4y3=0
将x0,y0作为变量求解二元一次方程组。
假设有二元一次方程组
a1x+b1y+c1=0;
a2x+b2y+c2=0
那么
x=(b1*c2-b2*c1)/(a1*b2-a2*b1)
y=(a2*c1-a1*c2)/(a1*b2-a2*b1)
#include<stdio.h> #include<string.h> #include<math.h> struct point{ double x,y; point(){} point(double x_,double y_){ x=x_,y=y_; } point operator -(const point &b)const{ return point(x-b.x,y-b.y); } double operator *(const point &b)const{//点积 return x*b.x+y*b.y; } double operator ^(const point &b)const{//叉积 return x*b.y-y*b.x; } }A,B,C,D; double cal(point p0,point p1,point p2){//小于0表示在p1处左折,大于0右折,等于0同线 return (p1-p0)^(p2-p0); } const double eps=1e-8; int main(){ int n,i; while(scanf("%d",&n)!=EOF){ puts("INTERSECTING LINES OUTPUT"); for(i=1;i<=n;i++){ scanf("%lf%lf%lf%lf",&A.x,&A.y,&B.x,&B.y); scanf("%lf%lf%lf%lf",&C.x,&C.y,&D.x,&D.y); if(fabs(cal(C,A,B))<eps&&fabs(cal(D,A,B))<eps) puts("LINE"); else if((B.x-A.x)*(D.y-C.y)==(D.x-C.x)*(B.y-A.y)) puts("NONE"); else{ double a1=A.y-B.y; double b1=B.x-A.x; double c1=A.x*B.y-B.x*A.y; double a2=C.y-D.y; double b2=D.x-C.x; double c2=C.x*D.y-D.x*C.y; double x=(b1*c2-b2*c1)/(a1*b2-a2*b1); double y=(a2*c1-a1*c2)/(a1*b2-a2*b1); printf("POINT %.2f %.2f\n",x,y); } } puts("END OF OUTPUT"); } return 0; }
POJ 1269 Intersecting Lines【判断直线相交】
标签:
原文地址:http://www.cnblogs.com/L-King/p/5728422.html