用C++写某一点到线段的最短距离
时间: 2023-05-21 13:01:35 浏览: 98
这个问题可以使用向量的方法来解决。假设点为P,线段的两个端点为A和B。首先,我们需要计算出向量AB和向量AP。然后,我们可以计算出向量AB和向量AP的点积,再除以向量AB的模长的平方,得到点P在线段AB上的投影点C。最后,我们可以计算出向量PC的模长,即为点P到线段AB的最短距离。
以下是用C语言实现的代码:
#include <stdio.h>
#include <math.h>
typedef struct {
double x;
double y;
} Point;
double distance(Point p, Point a, Point b) {
double dx = b.x - a.x;
double dy = b.y - a.y;
double u = ((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy);
Point c = {a.x + u * dx, a.y + u * dy};
double dx1 = p.x - c.x;
double dy1 = p.y - c.y;
return sqrt(dx1 * dx1 + dy1 * dy1);
}
int main() {
Point p = {1.0, 1.0};
Point a = {0.0, 0.0};
Point b = {2.0, 0.0};
printf("Distance from (%.1f, %.1f) to line segment (%.1f, %.1f) - (%.1f, %.1f) is %.3f\n", p.x, p.y, a.x, a.y, b.x, b.y, distance(p, a, b));
return 0;
}
输出结果为:
Distance from (1.0, 1.0) to line segment (0.0, 0.0) - (2.0, 0.0) is 1.000