用C语言编写函数实现美食评分排序(从文本文件中读入数据)以及对美食评分进行统计
时间: 2024-03-05 07:50:46 浏览: 76
好的,以下是用 C 语言编写函数实现美食评分排序(从文本文件中读入数据)以及对美食评分进行统计的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct food {
char name[20];
float score;
};
int cmp(const void *a, const void *b) {
struct food *fa = (struct food *)a;
struct food *fb = (struct food *)b;
return (fa->score > fb->score) ? -1 : 1;
}
void sort_and_count_foods_by_score(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error: Failed to open file %s\n", filename);
return;
}
int max_foods = 100;
struct food *foods = (struct food *)malloc(max_foods * sizeof(struct food));
int num_foods = 0;
float min_score = 100.0;
float max_score = 0.0;
float total_score = 0.0;
float avg_score = 0.0;
char line[50];
while (fgets(line, 50, fp) != NULL) {
char *name = strtok(line, ",");
char *score_str = strtok(NULL, ",");
float score = atof(score_str);
struct food f;
strcpy(f.name, name);
f.score = score;
if (score > max_score) {
max_score = score;
}
if (score < min_score) {
min_score = score;
}
total_score += score;
if (num_foods == max_foods) {
max_foods *= 2;
foods = (struct food *)realloc(foods, max_foods * sizeof(struct food));
}
foods[num_foods++] = f;
}
fclose(fp);
avg_score = total_score / num_foods;
qsort(foods, num_foods, sizeof(struct food), cmp);
printf("Sorted foods by score:\n");
for (int i = 0; i < num_foods; i++) {
printf("%s: %.1f\n", foods[i].name, foods[i].score);
}
printf("Statistics:\n");
printf("Number of foods: %d\n", num_foods);
printf("Minimum score: %.1f\n", min_score);
printf("Maximum score: %.1f\n", max_score);
printf("Average score: %.1f\n", avg_score);
free(foods);
}
int main() {
sort_and_count_foods_by_score("foods.txt");
return 0;
}
```
与上一个示例代码相比,这里增加了对美食评分的统计。具体来说,我们增加了四个变量:`min_score` 表示美食评分的最小值,`max_score` 表示美食评分的最大值,`total_score` 表示美食评分的总和,`avg_score` 表示美食评分的平均值。在读入每个美食时,我们更新这些变量的值。在排序完成后,我们输出这些统计结果。
请注意,这只是一个简单的示例代码,实际应用中还需要考虑各种边界情况和异常处理,比如文件不存在、文件格式错误等。
阅读全文