c++实现点到线段的距离
时间: 2023-10-15 18:07:18 浏览: 44
点到线段的距离可以分为以下几种情况:
1. 点在线段上的情况,距离为0。
2. 点在线段所在直线上但不在线段上的情况,距离为点到直线的距离。
3. 点在线段的延长线上但不在线段上的情况,距离为点到线段端点的距离中的最小值。
4. 点在线段的两端点之间的情况,距离为点到线段端点的距离中的最小值。
下面是一个实现:
```c
#include <stdio.h>
#include <math.h>
typedef struct {
double x;
double y;
} Point;
typedef struct {
Point start;
Point end;
} LineSegment;
double pointToLineSegmentDistance(Point p, LineSegment l) {
double x1 = l.start.x, y1 = l.start.y;
double x2 = l.end.x, y2 = l.end.y;
double x0 = p.x, y0 = p.y;
double cross = (x2 - x1) * (x0 - x1) + (y2 - y1) * (y0 - y1);
if (cross <= 0) {
return sqrt((x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1));
}
double d2 = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
if (cross >= d2) {
return sqrt((x0 - x2) * (x0 - x2) + (y0 - y2) * (y0 - y2));
}
double r = cross / d2;
double px = x1 + (x2 - x1) * r;
double py = y1 + (y2 - y1) * r;
return sqrt((x0 - px) * (x0 - px) + (y0 - py) * (y0 - py));
}
int main() {
Point p = {1, 1};
LineSegment l = {{0, 0}, {2, 0}};
printf("%f\n", pointToLineSegmentDistance(p, l)); // expect 1.000000
p = {-1, -1};
l = {{0, 0}, {2, 0}};
printf("%f\n", pointToLineSegmentDistance(p, l)); // expect 1.414214
p = {3, 0};
l = {{0, 0}, {2, 0}};
printf("%f\n", pointToLineSegmentDistance(p, l)); // expect 1.000000
p = {1, -1};
l = {{0, 0}, {2, 0}};
printf("%f\n", pointToLineSegmentDistance(p, l)); // expect 1.000000
p = {1, 1};
l = {{0, 0}, {1, 1}};
printf("%f\n", pointToLineSegmentDistance(p, l)); // expect 0.000000
p = {2, 2};
l = {{0, 0}, {1, 1}};
printf("%f\n", pointToLineSegmentDistance(p, l)); // expect 1.414214
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)