用c++实现任意点到直线的距离,要求使用类
时间: 2024-05-05 12:16:36 浏览: 14
这里是一个用C++实现的任意点到直线的距离的类:
```
#include <cmath>
class Point {
public:
double x;
double y;
};
class Line {
public:
double a;
double b;
double c;
Line(Point p1, Point p2) {
a = p2.y - p1.y;
b = p1.x - p2.x;
c = p2.x * p1.y - p1.x * p2.y;
}
double distance(Point p) {
return std::abs(a * p.x + b * p.y + c) / std::sqrt(a * a + b * b);
}
};
```
使用示例:
```
int main() {
Point p1 = {0, 0};
Point p2 = {1, 1};
Line line(p1, p2);
Point p = {2, 0};
double d = line.distance(p);
return 0;
}
```
其中,`Point`类表示点,`Line`类表示直线,`a`、`b`、`c`分别表示直线的一般式中的三个参数。在`Line`类的构造函数中,根据给定的两个点计算出直线的一般式参数。`distance`方法可以计算任意点到直线的距离。
相关问题
使用c++编写一个函数,点到直线的距离
假设直线的一般式为 Ax + By + C = 0,点的坐标为 (x0, y0),则点到直线的距离公式为:
d = |Ax0 + By0 + C| / sqrt(A^2 + B^2)
以下是使用 C++ 编写的函数:
```c++
#include <cmath>
double pointToLineDistance(double A, double B, double C, double x0, double y0) {
return std::abs(A * x0 + B * y0 + C) / std::sqrt(A * A + B * B);
}
```
其中,A、B、C 是直线的系数,x0、y0 是点的坐标。函数返回点到直线的距离。
c++ 点到直线的距离
点到直线的距离可以使用向量的方法来计算。假设直线上有两个点 $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)$,输出为点到直线的距离。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)