详见代码
View Code
1 /* 2 几何+线段相交 3 */ 4 #include<stdio.h> 5 #include<string.h> 6 #include<stdlib.h> 7 #include<algorithm> 8 #include<iostream> 9 #include<queue> 10 //#include<map> 11 #include<math.h> 12 using namespace std; 13 typedef long long ll; 14 //typedef __int64 int64; 15 const int maxn = 105; 16 const int inf = 0x7fffffff; 17 const double pi=acos(-1.0); 18 const double eps = 1e-8; 19 struct point { 20 double x,y; 21 }; 22 struct line{ 23 point a,b; 24 }; 25 line myline[ maxn ]; 26 27 double xmult( point a,point b,point c ){ 28 return ( a.x-c.x )*( b.y-c.y )-( a.y-c.y )*( b.x-c.x ); 29 } 30 bool inLine( line now,point p ){ 31 double minx,maxx,miny,maxy; 32 minx=min( now.a.x,now.b.x ); 33 maxx=max( now.a.x,now.b.x ); 34 miny=min( now.a.y,now.b.y ); 35 maxy=max( now.a.y,now.b.y ); 36 if( p.x>=minx&&p.x<=maxx&&p.y>=miny&&p.y<=maxy ) 37 return true; 38 else 39 return false; 40 } 41 bool intersect( line one,line two ){ 42 double d1,d2,d3,d4; 43 d1=xmult( two.a,one.b,one.a ); 44 d2=xmult( two.b,one.b,one.a ); 45 d3=xmult( one.a,two.a,two.b ); 46 d4=xmult( one.b,two.a,two.b ); 47 if( d1*d2<0&&d3*d4<0 ) 48 return true;//相互跨过 49 if( d1==0&&inLine( one,two.a )==true ) 50 return true; 51 if( d2==0&&inLine( one,two.b )==true ) 52 return true; 53 if( d3==0&&inLine( two,one.a )==true ) 54 return true; 55 if( d4==0&&inLine( two,one.b )==true ) 56 return true;//分别表示某个点在一条直线上的情况 57 return false; 58 } 59 60 int main(){ 61 int n; 62 while( scanf("%d",&n)!=EOF,n ){ 63 for( int i=0;i<n;i++ ){ 64 scanf("%lf%lf%lf%lf",&myline[ i ].a.x,&myline[ i ].a.y,&myline[ i ].b.x,&myline[ i ].b.y); 65 } 66 int sum=0;//交点的个数 67 for( int i=0;i<n;i++ ){ 68 for( int j=i+1;j<n;j++ ){ 69 if( intersect( myline[ i ],myline[ j ] )==true ) 70 sum++; 71 } 72 } 73 printf("%d\n",sum); 74 } 75 return 0; 76 }