C++代码写多个xy 坐标点怎么获取距离最近的
时间: 2024-02-09 20:07:57 浏览: 171
您可以通过计算每对点之间的距离,然后找到距离最短的一对点来获取距离最近的点。以下是C++代码示例:
```c++
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
struct Point {
int x, y;
Point(int x, int y) : x(x), y(y) {}
};
double distance(Point p1, Point p2) {
int dx = p1.x - p2.x;
int dy = p1.y - p2.y;
return sqrt(dx * dx + dy * dy);
}
int main() {
vector<Point> points = { {1, 2}, {3, 4}, {5, 6}, {7, 8} };
int n = points.size();
double min_dist = distance(points[0], points[1]);
int idx1 = 0, idx2 = 1;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
double dist = distance(points[i], points[j]);
if (dist < min_dist) {
min_dist = dist;
idx1 = i;
idx2 = j;
}
}
}
cout << "The closest points are (" << points[idx1].x << ", " << points[idx1].y << ") and (" << points[idx2].x << ", " << points[idx2].y << ")" << endl;
cout << "Their distance is " << min_dist << endl;
return 0;
}
```
在上面的代码中,我们使用`Point`结构体表示二维坐标点,`distance`函数用于计算两个点之间的距离。我们先初始化一个点集`points`,然后使用两个嵌套的循环遍历每对点之间的距离,找到距离最短的一对点。最后输出这对点和它们之间的距离。
阅读全文