用C语言编写函数实现美食评分排序(从文本文件中读入数据)以及对美食评分进行统计(总程序的一部分)
时间: 2024-01-18 21:04:22 浏览: 24
好的,我可以为您提供一种实现方式。首先,我们可以定义一个结构体来表示每种美食,包括名称和评分:
```c
typedef struct {
char name[50];
int score;
} Food;
```
然后,我们可以定义一个函数来从文本文件中读入数据并将其存储到一个数组中:
```c
void read_food_data(Food *foods, int *count) {
FILE *file = fopen("food_data.txt", "r");
if (file == NULL) {
printf("Failed to open file.\n");
return;
}
int i = 0;
while (!feof(file)) {
fscanf(file, "%s %d", foods[i].name, &foods[i].score);
i++;
}
fclose(file);
*count = i;
}
```
接下来,我们可以定义一个函数来对美食评分进行排序:
```c
void sort_food_by_score(Food *foods, int count) {
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (foods[j].score < foods[j + 1].score) {
Food temp = foods[j];
foods[j] = foods[j + 1];
foods[j + 1] = temp;
}
}
}
}
```
最后,我们可以定义一个函数来对美食评分进行统计:
```c
void calculate_food_score_statistics(Food *foods, int count) {
int total_score = 0;
for (int i = 0; i < count; i++) {
total_score += foods[i].score;
}
double average_score = (double)total_score / count;
printf("Total number of foods: %d\n", count);
printf("Total score of all foods: %d\n", total_score);
printf("Average score of all foods: %.2f\n", average_score);
}
```
完整的程序可以像这样:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[50];
int score;
} Food;
void read_food_data(Food *foods, int *count) {
FILE *file = fopen("food_data.txt", "r");
if (file == NULL) {
printf("Failed to open file.\n");
return;
}
int i = 0;
while (!feof(file)) {
fscanf(file, "%s %d", foods[i].name, &foods[i].score);
i++;
}
fclose(file);
*count = i;
}
void sort_food_by_score(Food *foods, int count) {
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (foods[j].score < foods[j + 1].score) {
Food temp = foods[j];
foods[j] = foods[j + 1];
foods[j + 1] = temp;
}
}
}
}
void calculate_food_score_statistics(Food *foods, int count) {
int total_score = 0;
for (int i = 0; i < count; i++) {
total_score += foods[i].score;
}
double average_score = (double)total_score / count;
printf("Total number of foods: %d\n", count);
printf("Total score of all foods: %d\n", total_score);
printf("Average score of all foods: %.2f\n", average_score);
}
int main() {
int count = 0;
Food *foods = malloc(sizeof(Food) * 100);
read_food_data(foods, &count);
sort_food_by_score(foods, count);
calculate_food_score_statistics(foods, count);
free(foods);
return 0;
}
```
需要注意的是,这里假设美食数据存储在名为“food_data.txt”的文本文件中,并且文件中的每一行都包含美食的名称和评分,以空格分隔。如果您的数据格式不同,需要相应地修改代码。