c++求两个线段的交点

#include<cstdio>
#include<iostream>
using namespace std;
struct point
{
    double x;
    double y;
};
struct segment{
point start;
point end;
};
double multi(point a,point b,point c){
return (a.x-c.x)*(b.y-c.y)-(b.x-c.x)*(a.y-c.y);
}
int across(segment v1,segment v2){
if(max(v1.start.x,v1.end.x)>=min(v2.start.x,v2.end.x)&&
max(v2.start.x,v2.end.x)>=min(v1.start.x,v1.end.x)&&
   max(v1.start.y,v1.end.y)>=min(v2.start.y,v2.end.y)&&
max(v2.start.y,v2.end.y)>=min(v1.start.y,v1.end.y)&&
   multi(v2.start,v1.end,v1.start)*multi(v1.end,v2.end,v1.start)>0&&
   multi(v1.start,v2.end,v2.start)*multi(v2.end,v1.end,v2.start)>0)
   return 1;
   return 0;
}
point * intersection(segment u,segment v){
point p;
if(across(u,v))
{
    p.x=(multi(v.end,u.end,v.start)*v.start.x-multi(v.start,u.end,u.start)*v.end.x)
    /(multi(v.end,u.end,v.start)-multi(v.start,u.end,u.start));
    p.y=(multi(v.end,u.end,v.start)*v.start.y-multi(v.start,u.end,u.start)*v.end.y)
    /(multi(v.end,u.end,v.start)-multi(v.start,u.end,u.start));
    return &p;
}
return NULL;
}


int main(void){
segment m,n;
point *f;
cout<<"请输入第一个向量的头x,y:"<<endl;
cin>>m.start.x>>m.start.y;
cout<<"请输入第一个向量的尾x,y:"<<endl;
cin>>m.end.x>>m.end.y;
cout<<"请输入第二个向量的头x,y:"<<endl;
cin>>n.start.x>>n.start.y;
cout<<"请输入第二个向量的尾x,y:"<<endl;
cin>>n.end.x>>n.end.y;

if(intersection(m,n)!=NULL)
{
    f=intersection(m,n);
}
cout<<"答案是:"<<" x:"<<f->x<<"  y:"<<f->y<<endl;
}

你可能感兴趣的:(C++,线段交点)