題目意思:
給出8個數值 = 4個座標 = 2條直線
問兩條直線的關係: 相交(交點), 共線,平行;
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <algorithm>#include <queue>using namespace std;#define INF 0x3f3f3f3f#define eps 1e-8const int maxn = 1000+3; int N;struct Point{ double x; double y; Point(double a = 0.0, double b = 0.0) { x = a; y = b; }};struct Line{ Point u; Point v;} L1,L2;int Sig(double x){ return (x > eps) - (x < -eps);}double Mult(const Point &p0, const Point &p1, const Point &p2){ return (p1.x-p0.x)*(p2.y-p0.y) - (p2.x-p0.x)*(p1.y-p0.y);}double Rake(Line L) //求斜率{ if(!Sig(L.v.x-L.u.x)) return INF; return (L.v.y - L.u.y)/(L.v.x - L.u.x);}int Intersect(Line L1, Line L2) //line instersect in a point{ int a = Sig(Mult(L2.u, L1.u, L2.v)); int b = Sig(Mult(L2.u, L1.v, L2.v)); if( a*b<0) //相交 return 1; else if( a*b == 0 ) //共線 return 0; else //相離 (包括平行) return -1;} int main(){#ifndef ONLINE_JUDGE freopen("in","r",stdin);#endif cin>>N; cout<<"INTERSECTING LINES OUTPUT"<<endl; double k1,k2,b1,b2,x,y; while(N--) { cin>>L1.u.x>>L1.u.y>>L1.v.x>>L1.v.y>>L2.u.x>>L2.u.y>>L2.v.x>>L2.v.y; int flag = Intersect(L1, L2); if(flag == 1) { k1 = Rake(L1); b1 = L1.u.y - k1*L1.u.x; k2 = Rake(L2); b2 = L2.u.y - k2*L2.u.x; x = (b2-b1) / (k1-k2); y = k1*x + b1; printf("POINT %.2f %.2f\n",x,y); } else if(flag == 0) cout<<"LINE"<<endl; else cout<<"NONE"<<endl; } cout<<"END OF OUTPUT"<<endl; return 0;}
起初我還判斷了,斜率等於無窮的情況,後來發現,除以無窮大 就是0了...所以不需要判斷. 判斷代碼:
// if(!Sig(INF-k1) || !Sig(INF-k2)) //存在其中一條直線垂直x軸// {// if(!Sig(INF-k1)) //L1 垂直x軸// {// x = L1.u.x;// y = k2*x + b2;// }// else //L2 垂直x軸// {// x = L2.u.x;// y = k1*x + b1;// }// }// else// { x = (b2-b1) / (k1-k2); y = k1*x + b1;// }