以下是使用C语言编写的程序,可以求给定n个实数在实轴上相邻两个数之间的最大差值:

#include <stdio.h>
#include <stdlib.h>

// 比较函数,用于快速排序
int compare(const void *a, const void *b) {
    return (*(double*)a - *(double*)b);
}

double maxGap(double arr[], int n) {
    // 如果只有一个数,则最大差值为0
    if (n <= 1)
        return 0;

    // 对数组进行排序
    qsort(arr, n, sizeof(double), compare);

    double max = arr[1] - arr[0];
    for (int i = 2; i < n; i++) {
        double gap = arr[i] - arr[i-1];
        if (gap > max)
            max = gap;
    }

    return max;
}

int main() {
    int n;
    printf("请输入实数的个数:");
    scanf("%d", &n);

    double *arr = (double*)malloc(n * sizeof(double));

    for (int i = 0; i < n; i++) {
        printf("请输入第%d个实数:", i+1);
        scanf("%lf", &arr[i]);
    }

    double max_gap = maxGap(arr, n);
    printf("最大差值为:%lf\n", max_gap);

    free(arr);

    return 0;
}

该程序首先使用快速排序对给定的实数数组进行排序,然后遍历排序后的数组,计算相邻两个数之间的差值,并找出最大差值。请注意,为了方便起见,这里使用了动态内存分配来存储输入的实数数组,因此在程序结束后需要使用free函数释放内存。


原文地址: https://www.cveoy.top/t/topic/mmrD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录