一维最近点对——C语言代码
时间: 2023-10-21 07:04:26 浏览: 43
以下是一维最近点对的C语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct point {
int x;
int y;
};
int compare(const void *a, const void *b) {
return ((struct point *)a)->x - ((struct point *)b)->x;
}
float distance(struct point a, struct point b) {
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}
float closest_pair(struct point *points, int n) {
if (n <= 1) {
return INFINITY;
}
qsort(points, n, sizeof(struct point), compare);
float min_distance = INFINITY;
for (int i = 0; i < n - 1; i++) {
float d = distance(points[i], points[i + 1]);
if (d < min_distance) {
min_distance = d;
}
}
return min_distance;
}
int main() {
int n;
printf("Enter the number of points: ");
scanf("%d", &n);
struct point *points = malloc(n * sizeof(struct point));
for (int i = 0; i < n; i++) {
printf("Enter x and y coordinates of point %d: ", i + 1);
scanf("%d %d", &points[i].x, &points[i].y);
}
float min_distance = closest_pair(points, n);
printf("The closest pair of points has distance: %.2f\n", min_distance);
free(points);
return 0;
}
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)