sakura十弎 2016-08-24 07:44 采纳率: 100%
浏览 898
已结题

修改程序,打印最近点对的坐标;修改程序,计算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

  • 写回答

1条回答 默认 最新

  • 看得到你的人头 2016-08-24 08:29
    关注

    该了一个看看是不是你想要的吧
    #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);
    }
    运行结果如下:
    图片说明

    评论

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python