写一段c语言代码实现以下功能:有5个学生,每个学生有3门课程的成绩,从键盘输入学生数据(包括学号,姓名,3门课程成绩),计算出平均成绩,将原有数据和计算出的平均分数存放在磁盘文件”stud“中
时间: 2024-01-01 08:05:42 浏览: 81
好的,以下是实现题目要求的 C 语言代码:
```c
#include <stdio.h>
struct Student {
int id;
char name[20];
float score[3];
float average;
};
int main() {
struct Student students[5];
FILE *fp;
// 输入学生数据
for (int i = 0; i < 5; i++) {
printf("请输入第%d个学生的学号、姓名和3门课程成绩:\n", i + 1);
scanf("%d %s %f %f %f", &students[i].id, students[i].name, &students[i].score[0], &students[i].score[1], &students[i].score[2]);
// 计算平均成绩
students[i].average = (students[i].score[0] + students[i].score[1] + students[i].score[2]) / 3;
}
// 将数据存入磁盘文件
fp = fopen("stud", "w");
for (int i = 0; i < 5; i++) {
fprintf(fp, "%d %s %.2f %.2f %.2f %.2f\n", students[i].id, students[i].name, students[i].score[0], students[i].score[1], students[i].score[2], students[i].average);
}
fclose(fp);
printf("学生数据已存入磁盘文件stud中!\n");
return 0;
}
```
以上代码通过定义一个结构体 `Student` 存储每个学生的学号、姓名、3门课程成绩和平均成绩。程序先通过循环输入每个学生的数据,并计算平均成绩。最后将所有学生的数据和平均成绩存入磁盘文件 "stud" 中,利用 `fprintf` 函数进行格式化输出。存储到文件后程序输出提示信息,提示数据已经存入文件中。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)