用C++写一个能实现给定 � n 个二维欧几里得平面上的点 � 1 , � 2 , … , � � p 1 ,p 2 ,…,p n ,请输出距离最近的两个点的距离。的代码
时间: 2023-09-08 13:04:25 浏览: 131
### 回答1:
可以采用最简单的暴力法来实现,具体代码如下:#include <stdio.h>
#include <math.h>
int main()
{
int n;
scanf("%d",&n);
double x[n],y[n];
for(int i=0;i<n;i++)
scanf("%lf %lf",&x[i],&y[i]);
double min=99999999.0;
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(min>sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])))
min=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
printf("%.2lf\n",min);
return 0;
}
### 回答2:
#include <stdio.h>
#include <math.h>
typedef struct Point {
int x;
int y;
} Point;
double euclidean_distance(Point p1, Point p2) {
int dx = p1.x - p2.x;
int dy = p1.y - p2.y;
return sqrt(dx*dx + dy*dy);
}
double closest_distance(Point points[], int n) {
double min_distance = -1;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
double distance = euclidean_distance(points[i], points[j]);
if (min_distance == -1 || distance < min_distance) {
min_distance = distance;
}
}
}
return min_distance;
}
int main() {
int n;
printf("请输入点的个数n:");
scanf("%d", &n);
Point points[n];
for (int i = 0; i < n; i++) {
printf("请输入第%d个点的坐标(x y):", i+1);
scanf("%d %d", &points[i].x, &points[i].y);
}
double closest = closest_distance(points, n);
printf("距离最近的两个点的距离:%f\n", closest);
return 0;
}
### 回答3:
以下是用C语言编写的实现给定n个二维欧几里得平面上的点,输出距离最近的两个点距离的代码:
```
#include <stdio.h>
#include <math.h>
struct Point {
int x;
int y;
};
double calculateDistance(struct Point p1, struct Point p2) {
double distance;
distance = sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
return distance;
}
double findClosestDistance(struct Point points[], int n) {
double minDistance = __DBL_MAX__;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
double distance = calculateDistance(points[i], points[j]);
if (distance < minDistance) {
minDistance = distance;
}
}
}
return minDistance;
}
int main() {
int n;
printf("请输入点的数量:");
scanf("%d", &n);
struct Point points[n];
for (int i = 0; i < n; i++) {
printf("请输入第%d个点的x坐标:", i+1);
scanf("%d", &points[i].x);
printf("请输入第%d个点的y坐标:", i+1);
scanf("%d", &points[i].y);
}
double closestDistance = findClosestDistance(points, n);
printf("最近的两个点的距离是:%f\n", closestDistance);
return 0;
}
```
这段代码首先定义了一个结构体`Point`来表示点的坐标,并且定义了两个函数。`calculateDistance()`函数用来计算两个点之间的欧几里得距离,`findClosestDistance()`函数用来找到所有点中距离最近的两个点的距离。
在`main()`函数中,首先让用户输入点的数量n,并且使用循环依次输入每个点的坐标。然后调用`findClosestDistance()`函数找到距离最近的两个点的距离,并输出结果。
阅读全文