常规而又直接的计算几何判断直线是否相交题目,如果相交,求相交的交点
在这里要注意两点:
1、scanf()输入double型数据要用%lf
2、用一般式(Ax+By+C=0)判断的直线时候记住重合的充要条件是 A2B1-A1B2==0 && A1C2-C1A2==0 && B1C2-C1B2==0(初高中的几何知识全还给老师了,(-_-))
我犯错的时候是用A2B1-A1B2==0 && (A1C2-C1A2==0) ||( B1C2-C1B2==0)判断的,WA两次
#include<iostream>
#include<cstdio>
struct POINT
{
double x;
double y;
POINT():x(0),y(0) {};
POINT(double _x_,double _y_):x(_x_),y(_y_) {};
};
struct LINE
{
POINT a;
POINT b;
LINE() {};
LINE(POINT _a_,POINT _b_):a(_a_),b(_b_) {};
};
void Coeefficient(const LINE & L,double &A,double &B,double &C)
{
A = L.b.y-L.a.y;
B = L.a.x-L.b.x;
C = L.b.x*L.a.y-L.a.x*L.b.y;
}
POINT Intersection(const LINE &A,const LINE &B)
{
double A1,B1,C1;
double A2,B2,C2;
Coeefficient(A,A1,B1,C1);
Coeefficient(B,A2,B2,C2);
POINT I(0,0);
I.x = - (B2*C1-B1*C2) / (A1*B2-A2*B1);
I.y = (A2*C1-A1*C2) / (A1*B2-A2*B1);
return I;
}
bool IsParallel(const LINE &A,const LINE &B)
{
double A1,B1,C1;
double A2,B2,C2;
Coeefficient(A,A1,B1,C1);
Coeefficient(B,A2,B2,C2);
//共线不算平行
/* return (A1*B2==A2*B1)&&((A1*C2!=A2*C1)||(B1*C2!=B2*C1));*/
//共线算平行
return (A1*B2==A2*B1);
}
bool IsPa(const LINE &A,const LINE &B)
{
double A1,B1,C1;
double A2,B2,C2;
Coeefficient(A,A1,B1,C1);
Coeefficient(B,A2,B2,C2);
return (A1*B2==A2*B1)&&(A1*C2==A2*C1)&&(B1*C2==B2*C1);
}
bool IsIntersect(const LINE &A,const LINE &B)
{
return !IsParallel(A,B);
}
int main()
{
//freopen("in.txt","r",stdin);
int n;
scanf("%d",&n);
printf("INTERSECTING LINES OUTPUT\n");
while(n--)
{
LINE A,B;
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&A.a.x,&A.a.y,&A.b.x,&A.b.y,&B.a.x,&B.a.y,&B.b.x,&B.b.y);
if(IsIntersect(A,B))
{
POINT I=Intersection(A,B);
printf("POINT %.2f %.2f\n",I.x,I.y);
}
else if(IsPa(A,B))
{
printf("LINE\n");
}
else printf("NONE\n");
}
printf("END OF OUTPUT\n");
return 0;
}