线段与线段交点的推导公式

知识储备: 

叉乘:http://blog.csdn.net/nightmare_ak/article/details/77199940 
定比分点法:http://blog.csdn.net/nightmare_ak/article/details/77917293

对于线段,只要先判断是否相交,就可以转化成直线求交点了

这里写图片描述

附模板:

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

const int MAXN = 20 + 5;

struct Pos
{
    double _x, _y;

    Pos(double x=0.0,double y=0.0):_x(x),_y(y){}
}up[MAXN], down[MAXN];

double Cross(Pos p1, Pos p2, Pos p0)//叉乘
{
    return (p1._x - p0._x)*(p2._y - p0._y) - (p2._x - p0._x)*(p1._y - p0._y);
}

bool isColide(Pos p1,Pos p2,Pos p3,Pos p4)//判断是否相交,直线p1p2与线段p3p4
{
    double tmp = Cross(p2, p3, p1)*Cross(p2, p4, p1);
    return tmp < 0.0 || fabs(tmp) < 1e-6;
}

Pos getPoint(Pos p1, Pos p2, Pos p3, Pos p4)//求出交点,直线(线段)p1p2与直线(线段)p3p4
{//t=lamta/(1+lamta)
    double x1 = p1._x, y1 = p1._y;
    double x2 = p2._x, y2 = p2._y;
    double x3 = p3._x, y3 = p3._y;
    double x4 = p4._x, y4 = p4._y;
    double t = ((x2 - x1)*(y3 - y1) - (x3 - x1)*(y2 - y1)) / ((x2 - x1)*(y3 - y4) - (x3 - x4)*(y2 - y1));
    return Pos(x3 + t*(x4 - x3), y3 + t*(y4 - y3));
}

int main()
{
    return 0;
}
posted @ 2018-06-02 21:06  wanhong  阅读(3177)  评论(0编辑  收藏  举报