首页 > 代码库 > 判断两线段相交

判断两线段相交

 

 

 

#include <iostream>#include <cstdio>#include <algorithm>#include <string.h>#include <stdlib.h>using namespace std;int n;struct point{    double x;    double y;};struct v{    point s;    point e;} q[102];int sum;double multi(struct point p1,struct point p2,struct point p0){    return (p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y);}int main(){    while(scanf("%d",&n)!=EOF&&n!=0)    {        sum=0;        for(int i=0; i<n; i++)        {            scanf("%lf%lf%lf%lf",&q[i].s.x,&q[i].s.y,&q[i].e.x,&q[i].e.y);        }        for(int i=0; i<n; i++)        {            for(int j=i+1; j<n; j++)            {                if(max(q[i].s.x,q[i].e.x)>=min(q[j].s.x,q[j].e.x)&&                        min(q[i].s.x,q[i].e.x)<=max(q[j].s.x,q[j].e.x)&&                        max(q[i].s.y,q[i].e.y)>=min(q[j].s.y,q[j].e.y)&&                        min(q[i].s.y,q[i].e.y)<=max(q[j].s.y,q[j].e.y)&&                        multi(q[j].s,q[i].e,q[i].s)*multi(q[i].e,q[j].e,q[i].s)>=0&&                        multi(q[i].s,q[j].e,q[j].s)*multi(q[j].e,q[i].e,q[j].s)>=0)                    sum++;            }        }        cout<<sum<<endl;    }    return 0;}

  

判断两线段相交