用C语言随机读写的方式计算1、3、5条记录的两门课的平均成绩学生数据为:{ {{2020B200301},”刘滨”,”男”,18,{2020,9,20},70,85}, {{2020B200302},”阚美娟”,”女”,17,{2020,9,20},87,95, {{2020B200303},”胡大勇”,”男”,17,{2020,9,20},69,80}, {{2020B200305},”黎丽”,”女”,18,{2020,9,20},68,88}, {{2020B200309},”金鑫”,”男”,19,{2019,9,1},90,85} }
时间: 2023-12-17 18:04:21 浏览: 22
好的,我理解了你的问题。以下是用C语言随机读写的方式计算1、3、5条记录的两门课的平均成绩的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char id[12];
char name[20];
char sex[6];
int age;
int date[3];
int score1;
int score2;
} Student;
int main() {
FILE *fp;
Student stu[5];
int i, pos, sum1 = 0, sum2 = 0;
float avg1, avg2;
// 以二进制的形式打开文件
if ((fp = fopen("data.bin", "rb+")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
// 随机读取记录
pos = 0;
fseek(fp, pos * sizeof(Student), SEEK_SET);
fread(&stu[0], sizeof(Student), 1, fp);
pos = 2;
fseek(fp, pos * sizeof(Student), SEEK_SET);
fread(&stu[1], sizeof(Student), 1, fp);
pos = 4;
fseek(fp, pos * sizeof(Student), SEEK_SET);
fread(&stu[2], sizeof(Student), 1, fp);
// 计算平均成绩
sum1 = stu[0].score1 + stu[1].score1 + stu[2].score1;
sum2 = stu[0].score2 + stu[1].score2 + stu[2].score2;
avg1 = (float)sum1 / 3;
avg2 = (float)sum2 / 3;
// 输出结果
printf("1st course average score: %.2f\n", avg1);
printf("2nd course average score: %.2f\n", avg2);
// 关闭文件
fclose(fp);
return 0;
}
```
注意,以上代码需要先将数据保存为二进制文件 `data.bin`,然后才能够进行随机读写。另外,这里假设文件中有5条记录,但只计算了1、3、5条记录的成绩平均值。如果需要计算其他记录的成绩平均值,可以根据需要修改代码。