修改程序,打印最近点对的坐标;修改程序,计算d维空间中的最近点对。(程序见正文)

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct { float x; float y; } point;
float distance(point a, point b)
{
    float dx = a.x - b.x, dy = a.y - b.y;
    return sqrt(dx*dx + dy*dy);
}
float randFloat()
{
    return 1.0*rand() / RAND_MAX;
}
int main()
{
    //float d = atof(argv[2]);
    float d;
    scanf_s("%f", &d);
    int i, j, cnt = 0;
    //N = atoi(argv[1]);
    int N;
    scanf_s("%d", &N);
    point *a = (point  *)malloc(N*(sizeof(*a)));
    for (i = 0; i < N; i++)
    {
        a[i].x = randFloat(); a[i].y = randFloat();
    }
    for (i = 0; i < N-1; i++)
    for (j = i + 1; j < N; j++)
    if (distance(a[i], a[j]) < d) cnt++;
    printf("%d edges shorter than %f\n", cnt, d);
}

这个程序是对于N个随机产生的单位正方形中的点,统计可以被小于d的直线连接的点对数。

这是算法:c语言实现的习题,如果有人有习题解答的话,请发给我,非常感激。
2539273479@qq.com

该了一个看看是不是你想要的吧
#include
#include
#include
typedef struct
{
float x; float y;
}point;
float distance(point a, point b)
{
float dx = a.x - b.x, dy = a.y - b.y;
return sqrt(dx*dx + dy*dy);
}
float randFloat()
{
return 1.0*rand() / RAND_MAX;
}
int main()
{
int i, j, cnt = 0;
int N;
printf("请输入个数N的值:\n");
scanf_s("%d", &N);
point a = (point *)malloc(N(sizeof(*a)));
for (i = 0; i < N; i++)
{
a[i].x = randFloat(); a[i].y = randFloat();
}
int miniDistance=1000;//记录最小距离
int FirstPoint=0;//记录最近点的坐标
int SecondPoint=0;//记录最近点的坐标
for (i = 0; i < N-1; i++)
for (j = i + 1; j < N; j++)
if (distance(a[i], a[j]) < miniDistance)//每次计算两点的距离与最小的距离比较,如果比之前最小的还要小则执行下面的程序
{
miniDistance=distance(a[i],a[j]);
FirstPoint=i;
SecondPoint=j;
}
printf("最近点的坐标为:\n");
printf("(%f,%f) (%f,%f)\n",a[FirstPoint].x,a[FirstPoint].y,a[SecondPoint].x,a[SecondPoint].y);
}
运行结果如下:
图片说明