冬奥会国家金牌数量排序算法实现 - C语言代码示例
#include <stdio.h> #include <stdlib.h> #include <string.h>
#define MAX_COUNTRY_NUM 100 // 最多支持的国家数量 #define MAX_GOLD_NUM 100 // 每个国家最多获得的金牌数量
// 国家结构体 typedef struct { char name[20]; // 国家名称 int golds[MAX_GOLD_NUM]; // 该国家获得的金牌数量 int gold_num; // 该国家获得的金牌数量 } Country;
// 从文件中读取数据到内存 void read_data_from_file(Country *countries, int *country_num) { FILE *fp = fopen('woGolds.txt', 'r'); if (fp == NULL) { printf('Failed to open file woGolds.txt\n'); exit(1); }
*country_num = 0; // 初始化国家数量为0
while (!feof(fp)) {
char line[100];
fgets(line, 100, fp);
if (strlen(line) == 0) {
continue;
}
char *p = strtok(line, ' ');
if (p == NULL) {
continue;
}
// 新增一个国家
strcpy(countries[*country_num].name, p);
countries[*country_num].gold_num = 0;
// 读取该国家获得的金牌数量
while ((p = strtok(NULL, ' ')) != NULL) {
countries[*country_num].golds[countries[*country_num].gold_num++] = atoi(p);
}
(*country_num)++; // 国家数量加1
}
fclose(fp);
}
// 将数据从内存写入文件 void write_data_to_file(Country *countries, int country_num) { FILE *fp = fopen('woGolds_sort.txt', 'w'); if (fp == NULL) { printf('Failed to open file woGolds_sort.txt\n'); exit(1); }
for (int i = 0; i < country_num; i++) {
fprintf(fp, '%s', countries[i].name);
for (int j = 0; j < countries[i].gold_num; j++) {
fprintf(fp, ' %d', countries[i].golds[j]);
}
fprintf(fp, '\n');
}
fclose(fp);
}
// 比较函数,用于qsort排序 int cmp(const void *a, const void *b) { Country *ca = (Country *)a; Country *cb = (Country *)b; int sum_a = 0, sum_b = 0; for (int i = 0; i < ca->gold_num; i++) { sum_a += ca->golds[i]; } for (int i = 0; i < cb->gold_num; i++) { sum_b += cb->golds[i]; } return sum_b - sum_a; }
int main() { Country countries[MAX_COUNTRY_NUM]; int country_num;
// 从文件读取数据到内存
read_data_from_file(countries, &country_num);
// 输出排序前的各个国家的金牌数量列表
printf('排序前\n');
for (int i = 0; i < country_num; i++) {
printf('%s', countries[i].name);
for (int j = 0; j < countries[i].gold_num; j++) {
printf(' %d', countries[i].golds[j]);
}
printf('\n');
}
// 对国家金牌数量进行排序
qsort(countries, country_num, sizeof(Country), cmp);
// 将排序后的数据写入文件
write_data_to_file(countries, country_num);
// 从文件读取排序后的数据到内存
read_data_from_file(countries, &country_num);
// 输出排序后的各个国家的金牌数量列表
printf('排序后\n');
for (int i = 0; i < country_num; i++) {
printf('%s', countries[i].name);
for (int j = 0; j < countries[i].gold_num; j++) {
printf(' %d', countries[i].golds[j]);
}
printf('\n');
}
return 0;
原文地址: https://www.cveoy.top/t/topic/n3to 著作权归作者所有。请勿转载和采集!