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

//判断直线是否相交,若相交,则返回交点
#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;
}
即使两条线段没有交点也没关系,因为它求的是直线的交点。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值