您的位置:首页 > 其它

判断直线是否相交,若相交,则返回交点

2016-08-05 11:22 357 查看
//判断直线是否相交,若相交,则返回交点
#include<iostream>
#include<vector>
using namespace std;
#define EPS 1e-6
typedef pair<double,double> CVector;
typedef pair<double,double> CPoint;
typedef pair<CPoint,CPoint> CLine;
bool IsZero(double x){
return -EPS<x&&x<EPS;
}
CVector operator - (CPoint p,CPoint q){
return CVector(p.first-q.first,p.second-q.second);
}
double operator ^ (CVector p,CVector q){
return p.first*q.second-p.second*q.first;
}
double dist(CLine p,CLine q){//该距离是当p//q是的距离
return p.second.second-q.second.second;
}
CPoint operator + (CPoint p,CVector q){
return CPoint(p.first+q.first,p.second+q.second);
}
CVector operator * (double k,CVector p){
return CVector(k*p.first,k*p.second);
}
void intersect(CLine l,CLine m){
double x=(m.first-l.first)^(l.second-l.first);
double y=(l.second-l.first)^(m.second-l.first);
if(IsZero(x+y)){
if(IsZero(dist(l,m))) printf("重合\n");
else printf("平行\n");
return ;
}
CPoint u=m.first+(x/(x+y))*(m.second-m.first);
printf("(%.2f,%.2f)\n",u.first,u.second);
}
int main()
{
vector<CLine> v;
CPoint p,q;
double x1,y1,x2,y2;
for(int i=0;i<2;i++){
cin>>x1>>y1>>x2>>y2;
p=CPoint(x1,y1),q=CPoint(x2,y2);
v.push_back(CLine(p,q));
}
intersect(v[0],v[1]);
return 0;
}
即使两条线段没有交点也没关系,因为它求的是直线的交点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: