请使用c语言完成以下功能的代码 (1)假设每个同学【学号为 9122001--9122100】有三门成绩 请随机生成 100 个同学成绩(成绩要求在 10-100 之间) (2) 将 100 个同学的学号成绩以二进制的形式保存在文件 b.dat 中。 (3) 再次从 b.dat 文件中依次读出各学生成绩,如果发现有学生成绩<60 分,则将该科目 成绩改为 0,保存回去,并打印该学生成绩。
时间: 2023-11-22 22:53:52 浏览: 65
DS28E01-100-C-code.zip_28E01_ds28e01-100_ds28e01加密芯片_ds28e01芯片代码
5星 · 资源好评率100%
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_STUDENTS 100
#define NUM_SUBJECTS 3
#define MIN_SCORE 10
#define MAX_SCORE 100
struct Student {
int id;
int scores[NUM_SUBJECTS];
};
void generate_students(struct Student *students) {
for (int i = 0; i < NUM_STUDENTS; i++) {
students[i].id = 9122001 + i;
for (int j = 0; j < NUM_SUBJECTS; j++) {
students[i].scores[j] = rand() % (MAX_SCORE - MIN_SCORE + 1) + MIN_SCORE;
}
}
}
void save_students_binary(const struct Student *students) {
FILE *fp = fopen("b.dat", "wb");
if (fp == NULL) {
printf("Failed to open file.\n");
return;
}
for (int i = 0; i < NUM_STUDENTS; i++) {
fwrite(&(students[i]), sizeof(struct Student), 1, fp);
}
fclose(fp);
}
void print_student(const struct Student *student) {
printf("Student ID: %d\n", student->id);
for (int i = 0; i < NUM_SUBJECTS; i++) {
printf("Subject %d: %d\n", i + 1, student->scores[i]);
}
}
void read_students_binary(struct Student *students) {
FILE *fp = fopen("b.dat", "rb+");
if (fp == NULL) {
printf("Failed to open file.\n");
return;
}
for (int i = 0; i < NUM_STUDENTS; i++) {
struct Student student;
fread(&student, sizeof(struct Student), 1, fp);
for (int j = 0; j < NUM_SUBJECTS; j++) {
if (student.scores[j] < 60) {
student.scores[j] = 0;
}
}
fseek(fp, -sizeof(struct Student), SEEK_CUR);
fwrite(&student, sizeof(struct Student), 1, fp);
print_student(&student);
}
fclose(fp);
}
int main() {
srand(time(NULL));
struct Student students[NUM_STUDENTS];
generate_students(students);
save_students_binary(students);
read_students_binary(students);
return 0;
}
```
阅读全文