qfedu-c-level/day14/homework/h4.c

63 lines
1.7 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 从score.txt中查找所有大于90分的学生信息学号、成绩并统计学生的数量和平均成绩。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct stu_s
{
int sid;
char dh; // 逗号
float score;
struct stu_s *next;
} STU;
int main()
{
FILE *fp = fopen("sxxx.dest", "rb");
// FILE *fp = fopen("score.txt", "r");
if (NULL == fp)
{
return 1;
}
// 计算文件大小
fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
printf("score.txt 文件大小: %ld B\n", file_size);
// 重置光标位置
fseek(fp, 0, SEEK_SET); // 等同于使用 rewind(fp);
// 按照 STU 的结构存储数据,计算出以存放学生数量
int stu_num = file_size / sizeof(STU);
printf("学生数量: %d\n", stu_num);
int above_90_stu_nums = 0; // 大于 90 分的学生数
float sum_score_of_above_90_stus = 0.0f; // 大于 90 分学生的总成绩
// printf("\n学号\t成绩\n");
for (int i = 0; i < stu_num; i++)
{
// 为新的链表节点分配内存空间
STU *s = calloc(1, sizeof(STU));
// 从文件中读取一个学生的数据
fread(s, sizeof(STU), 1, fp);
if (s->score > 90)
{
above_90_stu_nums++;
// printf("%.2f\n", s->score);
sum_score_of_above_90_stus += s->score;
}
free(s);
}
float avg_score_of_above_90_stus = sum_score_of_above_90_stus / above_90_stu_nums;
printf("\n大于 90 分的学生有 %d 位,他们的平均成绩为 %.2f\n", above_90_stu_nums, avg_score_of_above_90_stus);
fclose(fp);
return 0;
}