实验代码如下:

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

#define NUM_COUNTRIES 10 // 国家数量 #define FILENAME "woGolds.txt" // 存储金牌数量的文件名 #define SORTED_FILENAME "woGolds_sort.txt" // 排序后存储金牌数量的文件名

// 从键盘输入各个国家金牌数量到内存中 void inputGoldNums(int* goldNums) { printf("请输入%d个国家的金牌数量:\n", NUM_COUNTRIES); for (int i = 0; i < NUM_COUNTRIES; i++) { printf("国家%d的金牌数量:", i+1); scanf("%d", &goldNums[i]); } }

// 将内存中的各个国家金牌数量保存到文件中 void saveGoldNumsToFile(int* goldNums) { FILE* fp = fopen(FILENAME, "w"); if (fp == NULL) { printf("无法创建文件 %s\n", FILENAME); exit(1); } for (int i = 0; i < NUM_COUNTRIES; i++) { fprintf(fp, "%d ", goldNums[i]); } fclose(fp); }

// 从文件中读取各个国家金牌数量到内存中 void readGoldNumsFromFile(int* goldNums) { FILE* fp = fopen(FILENAME, "r"); if (fp == NULL) { printf("无法打开文件 %s\n", FILENAME); exit(1); } for (int i = 0; i < NUM_COUNTRIES; i++) { fscanf(fp, "%d", &goldNums[i]); } fclose(fp); }

// 输出各个国家的金牌数量列表 void printGoldNums(int* goldNums) { printf("各个国家的金牌数量列表:\n"); for (int i = 0; i < NUM_COUNTRIES; i++) { printf("国家%d:%d\n", i+1, goldNums[i]); } }

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

// 内存中各个国家的金牌数量排序处理 void sortGoldNums(int* goldNums) { qsort(goldNums, NUM_COUNTRIES, sizeof(int), cmp); }

// 将排序后的各个国家金牌数量保存到文件中 void saveSortedGoldNumsToFile(int* goldNums) { FILE* fp = fopen(SORTED_FILENAME, "w"); if (fp == NULL) { printf("无法创建文件 %s\n", SORTED_FILENAME); exit(1); } for (int i = 0; i < NUM_COUNTRIES; i++) { fprintf(fp, "%d ", goldNums[i]); } fclose(fp); }

// 从文件中读取排序后的各个国家金牌数量到内存中 void readSortedGoldNumsFromFile(int* goldNums) { FILE* fp = fopen(SORTED_FILENAME, "r"); if (fp == NULL) { printf("无法打开文件 %s\n", SORTED_FILENAME); exit(1); } for (int i = 0; i < NUM_COUNTRIES; i++) { fscanf(fp, "%d", &goldNums[i]); } fclose(fp); }

int main() { int goldNums[NUM_COUNTRIES];

// 输入各个国家金牌数量
inputGoldNums(goldNums);

// 将各个国家金牌数量保存到文件
saveGoldNumsToFile(goldNums);

// 从文件中读取各个国家金牌数量到内存中
readGoldNumsFromFile(goldNums);

// 输出各个国家的金牌数量列表
printGoldNums(goldNums);

// 内存中各个国家的金牌数量排序处理
sortGoldNums(goldNums);

// 将排序后的各个国家金牌数量保存到文件中
saveSortedGoldNumsToFile(goldNums);

// 从文件中读取排序后的各个国家金牌数量到内存中
readSortedGoldNumsFromFile(goldNums);

// 输出排序后的各个国家的金牌数量列表
printf("排序后的各个国家的金牌数量列表:\n");
for (int i = 0; i < NUM_COUNTRIES; i++) {
    printf("国家%d:%d\n", i+1, goldNums[i]);
}

return 0;
编程完成冬奥会国家金牌数量排序的实现。将2022北京冬奥会各个国家金牌数量存储在文件woGoldstxt中编程获取文件数据并进行金牌数量排序处理将排序后的结果存入一个新文件woGolds_sorttxt中并查看结果与实际结果是否相符。二、实验要求:1、理解并掌握该问题的实现方法;2、代码书写格式规范测试结果符合期望结果;3、通过编程完成各个国家金牌数量存储文件woGoldstxt在硬盘创建;4、通

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

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