c++ 点到直线的距离
时间: 2023-06-17 08:08:22 浏览: 73
点到直线的距离可以使用向量的方法来计算。假设直线上有两个点 $P_1(x_1, y_1)$ 和 $P_2(x_2, y_2)$,点 $Q(x, y)$ 是直线外的一点,则点 $Q$ 到直线的距离为:
$$\frac{|(P_2 - P_1) \times (Q - P_1)|}{|P_2 - P_1|}$$
其中 $\times$ 表示向量的叉积,$| \cdot |$ 表示向量的模长。
具体实现可以参考以下代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 计算两个向量的叉积
double crossProduct(double x1, double y1, double x2, double y2) {
return x1 * y2 - x2 * y1;
}
// 计算点到直线的距离
double distance(double x, double y, double x1, double y1, double x2, double y2) {
double dx = x2 - x1;
double dy = y2 - y1;
double cross = crossProduct(dx, dy, x - x1, y - y1);
double dist = sqrt(dx * dx + dy * dy);
return fabs(cross) / dist;
}
int main() {
double x, y, x1, y1, x2, y2;
cin >> x >> y >> x1 >> y1 >> x2 >> y2;
double d = distance(x, y, x1, y1, x2, y2);
cout << "Distance: " << d << endl;
return 0;
}
```
其中,输入的数据分别为点 $Q$ 的坐标 $(x, y)$,直线上两个点的坐标 $(x_1, y_1)$ 和 $(x_2, y_2)$,输出为点到直线的距离。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)