c++求三维空间点到线段的最短距离
时间: 2024-02-03 09:04:10 浏览: 163
以下是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;
}
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)