题意:
给了两条直线的两个的坐标。求他们相交的类型,如果正规相交并求出交点。
分析:
用点叉积,可以判断直线的相交类型(平行,共线,相交).大概是:
如果相交:设交点:p0(x0,y0),根据交点在两条直线上有方程:
(p1-p0)X(p2-p0)=0;
(p3-p0)X(p4-p0)=0;
展开就行了。
看代码就知道了:
#include<cstdio>
#include<cmath>
using namespace std;
struct node{
double x,y;
}p[5];
double t1,t2;
double count(node a,node b,node c){
return (a.x-c.x)*(b.y-c.y)-(a.y-c.y)*(b.x-c.x);
}
int cross_type(node a,node b,node c,node d){
if(!t1&&!t2) return 1; //t1=0&&t2=0就是共线。
if((b.x - a.x) * (d.y - c.y)==(d.x - c.x) * (b.y - a.y)) return 0; //平行
return 2; //相交
}
int main()
{
int t,flag;
scanf("%d",&t);
puts("INTERSECTING LINES OUTPUT");
while(t--){
for(int i=1;i<=4;i++)
scanf("%lf %lf",&p[i].x,&p[i].y);
t1=count(p[1],p[2],p[3]);
t2=count(p[1],p[2],p[4]);
flag=cross_type(p[1],p[2],p[3],p[4]);
if(flag==0) puts("NONE");
else if(flag==1) puts("LINE");
else{
p[0].x=(t1*p[4].x-t2*p[3].x)/(t1-t2);//求出x ,t1!=t2;
p[0].y=(t1*p[4].y-t2*p[3].y)/(t1-t2);
printf("POINT %.2f %.2f\n",p[0].x,p[0].y); //杯具啊,不能%lf啊,WA跪地!
}
}
puts("END OF OUTPUT");
}