c++求三维空间点到线段的最短距离
时间: 2024-02-03 17:04:10 浏览: 148
计算点到线段的最短距离
5星 · 资源好评率100%
以下是C++求三维空间点到线段的最短距离的代码实现:
```cpp
#include <iostream>
#include <cmath>
struct Point {
double x, y, z;
};
double GetDistance(Point A, Point B) {
return sqrt((A.x-B.x) * (A.x-B.x) + (A.y-B.y) * (A.y-B.y) + (A.z-B.z) * (A.z-B.z));
}
double GetNearest(Point A, Point B, Point C) {
double a = GetDistance(A, B);
double b = GetDistance(A, C);
double c = GetDistance(B, C);
if (a*a > b*b + c*c) return b;
if (b*b > a*a + c*c) return a;
double l = (a+b+c) / 2;
double s = sqrt(l*(l-a)*(l-b)*(l-c));
return 2*s/c;
}
int main() {
Point A = {1, 2, 3};
Point B = {4, 5, 6};
Point C = {7, 8, 9};
double shortestDistance = GetNearest(A, B, C);
std::cout << "The shortest distance from point A to line segment BC is: " << shortestDistance << std::endl;
return 0;
}
```
阅读全文