#include <math.h>
//定义点结构
struct point
{
double x;
double y;
};
//定义精度误差
const double eps = 1e-6;
//两点距离
double distance(const point &p1, const point &p2)
{
double dx = p1.x - p2.x, dy = p1.y - p2.y;
return sqrt(dx * dx + dy * dy);
}
//返回两点与原点组成的三角形面积的两倍
double multi(const point &p1, const point &p2)
{
return p1.x * p2.y - p1.y * p2.x;
}
//向量点乘
double dotmul(const point &p1, const point &p2)
{
return p1.x * p2.x + p1.y * p2.y;
}
//计算点到线段的距离,a,b定义那个线段,p为要计算的点
double pointToLine(point a, point b, const point& p)
{
point ab, o = {0};
ab.x = b.x - a.x; ab.y = b.y - a.y;
a.x -= p.x;
a.y -= p.y;
b.x -= p.x;
b.y -= p.y;
if (dotmul(a, ab) > -eps) return distance(o, a);
ab.x = -ab.x; ab.y = -ab.y;
if (dotmul(b, ab) > -eps) return distance(o, b);
return fabs(multi(a, b)) / distance(a, b);
}
//测试代码
#include <stdio.h>
int main()
{
point a = {0, 0}, b = {20, 39.9};
point p = {40, 80}; //换成10, 20会得到很小的结果
double dis = pointToLine(a, b, p);
printf("%f\n", dis);
return 0;
}