c++编写一个函数,通过两个点表示一条直线,然后求一点到这条线段的距离,注释写的详细一点
时间: 2024-02-23 14:59:04 浏览: 173
好的,下面是一个C++函数,可以用两个点的坐标表示一条直线,然后计算一个点到这条直线的距离:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 通过两点坐标计算直线斜率和截距
void calculate_slope_intercept(double x1, double y1, double x2, double y2, double& slope, double& intercept) {
slope = (y2 - y1) / (x2 - x1);
intercept = y1 - slope * x1;
}
// 计算点(x, y)到直线(ax + by + c = 0)的距离
double distance_to_line(double x, double y, double a, double b, double c) {
return abs(a * x + b * y + c) / sqrt(a * a + b * b);
}
// 计算点(x, y)到直线(x1, y1)-(x2, y2)的距离
double distance_to_line_segment(double x, double y, double x1, double y1, double x2, double y2) {
double slope, intercept;
calculate_slope_intercept(x1, y1, x2, y2, slope, intercept);
double a = slope;
double b = -1;
double c = intercept;
double x_min = min(x1, x2);
double x_max = max(x1, x2);
double y_min = min(y1, y2);
double y_max = max(y1, y2);
if (x < x_min || x > x_max || y < y_min || y > y_max) {
// 如果点(x, y)不在线段(x1, y1)-(x2, y2)所在的矩形范围内,则距离为点(x, y)到两个端点的距离的最小值
double distance1 = sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
double distance2 = sqrt((x - x2) * (x - x2) + (y - y2) * (y - y2));
return min(distance1, distance2);
} else {
// 如果点(x, y)在线段(x1, y1)-(x2, y2)所在的矩形范围内,则距离为点(x, y)到直线(ax + by + c = 0)的距离
return distance_to_line(x, y, a, b, c);
}
}
int main() {
double x, y, x1, y1, x2, y2;
cout << "请输入点的坐标(x, y):" << endl;
cin >> x >> y;
cout << "请输入直线上两点的坐标(x1, y1) 和 (x2, y2):" << endl;
cin >> x1 >> y1 >> x2 >> y2;
double distance = distance_to_line_segment(x, y, x1, y1, x2, y2);
cout << "点(" << x << ", " << y << ")到线段(" << x1 << ", " << y1 << ")-(" << x2 << ", " << y2 << ")的距离为:" << distance << endl;
return 0;
}
```
函数中`calculate_slope_intercept`函数用来通过两点坐标计算直线的斜率和截距,`distance_to_line`函数用来计算点到直线的距离,`distance_to_line_segment`函数用来计算点到线段的距离。如果点不在线段所在的矩形范围内,则距离为点到两个端点的距离的最小值。否则距离为点到直线的距离。
阅读全文