C语言中如何实现从大到小排列

如题所述

输入文件input.dat内容为:(数字以空格或换行符隔开)

运行程序后,输出文件output.dat内容为:

可见实现了数字从大到小排列

C语言源代码为:

#include <stdio.h>

#include <stdlib.h>

#define N 100

int cmp(const void *a, const void *b) {

    return *(int *)b - *(int *)a;

}

int main() {

    int arr[N], n = 0;

    FILE *fin = fopen("input.dat", "r");

    for (n = 0; n < N; ++n) {

        if (fscanf(fin, "%d", &arr[n]) == EOF)

            break;

    }

    qsort(arr, n, sizeof(int), cmp);

    FILE *fout = fopen("output.dat", "w");

    for (int i = 0; i < n; ++i)

        fprintf(fout, "%d ", arr[i]);

    fprintf(fout, "\n");

    fclose(fin);

    fclose(fout);

    return 0;

}

温馨提示:答案为网友推荐,仅供参考
相似回答