Problem Intersecting Lines (POJ 1269)
题目大意
给定两条直线,问两条直线是否重合,是否平行,或求出交点。
解题分析
主要用叉积做,可以避免斜率被0除的情况。
求交点P0: 已知P1 P2 P3 P4
运用 P0P1 X P0P2 = 0 和 P0P3 X P0P4 = 0
C++ 用%.2lf g++ 用 %.2f!!!
C++ 用%.2lf g++ 用 %.2f!!!
C++ 用%.2lf g++ 用 %.2f!!!
参考程序
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 7 #define eps 1e-8 8 9 struct P{ 10 double x,y; 11 12 P(){} 13 P(double x,double y):x(x),y(y){} 14 15 friend P operator +(P a,P b){ 16 return P(a.x+b.x,a.y+b.y); 17 } 18 friend P operator -(P a,P b){ 19 return P(a.x-b.x,a.y-b.y); 20 } 21 friend double operator *(P a,P b){ 22 return a.x * b.y - a.y * b.x ; 23 } 24 friend double operator /(P a,P b){ 25 return a.x * b.x + a.y * b.y ; 26 } 27 friend bool operator ==(P a,P b){ 28 return fabs(a.x-b.x) eps; 29 } 30 friend bool operator !=(P a,P b){ 31 return !(a==b); 32 } 33 friend bool operator <(P a,P b){ 34 if (fabs(a.y-b.y) return a.x<b.x; 35 return a.y<b.y; 36 } 37 friend double turn(P a,P b,P c){ //向量AB X 向量AC 38 return (b-a)*(c-a); 39 } 40 friend void print(P a){ 41 printf("%.2lf %.2lf\n",a.x,a.y); 42 } 43 }; 44 45 struct L{ 46 P a,b; 47 L(){} 48 L(P a,P b):a(a),b(b){} 49 friend P subl(L a){ //向量l 50 return P(a.b.x-a.a.x,a.b.y-a.a.y); 51 } 52 }; 53 54 bool online(L l,P p){ 55 if (fabs(turn(l.a,l.b,p)) return 1; 56 return 0; 57 } 58 P solve(double a1,double b1,double c1,double a2,double b2,double c2){ 59 P a; 60 a.x = (b1*c2-b2*c1)/(a1*b2-a2*b1); 61 a.y = (a1*c2-a2*c1)/(a2*b1-a1*b2); 62 return a; 63 } 64 void check(L lx,L ly){ 65 if (online(lx,ly.a) && online(lx,ly.b)) printf("LINE\n"); else 66 if (fabs(subl(lx)*subl(ly)) "NONE\n"); else 67 { 68 double x1=lx.a.x , y1=lx.a.y; 69 double x2=lx.b.x , y2=lx.b.y; 70 double x3=ly.a.x , y3=ly.a.y; 71 double x4=ly.b.x , y4=ly.b.y; 72 double a1 = y1 - y2 , b1 = x2 - x1 , c1 = x1*y2 - x2*y1 ; 73 double a2 = y3 - y4 , b2 = x4 - x3 , c2 = x3*y4 - x4*y3 ; 74 printf("POINT "); 75 print(solve(a1,b1,c1,a2,b2,c2)); 76 } 77 } 78 79 int main(){ 80 int T; 81 scanf("%d",&T); 82 printf("INTERSECTING LINES OUTPUT\n"); 83 while (T--){ 84 double x1,y1,x2,y2,x3,y3,x4,y4; 85 scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4); 86 P a(x1,y1),b(x2,y2),c(x3,y3),d(x4,y4); 87 L lx(a,b),ly(c,d); 88 check(lx,ly); 89 } 90 printf("END OF OUTPUT\n"); 91 }