有N个学生,每个学生的数据包括学号、姓名、3门课的成绩,从键盘输入N个学生的数据,要求: 1.打印出3门课的总平均成绩(结果保留两位小数) 2.打印平均分最高分学生的数据(包括学号、姓名、3门课成绩)c语言
时间: 2023-12-15 15:23:14 浏览: 94
以下是实现上述要求的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id; // 学号
char name[20]; // 姓名
float grade[3]; // 3门课成绩
float avg_grade; // 平均成绩
} Student;
int main() {
int n;
printf("请输入学生的个数:");
scanf("%d", &n);
Student *students = (Student*) malloc(sizeof(Student) * n);
if (students == NULL) {
printf("内存分配失败!");
return -1;
}
// 输入学生数据
for (int i = 0; i < n; i++) {
printf("请输入第%d个学生的数据(学号、姓名、3门课成绩):", i+1);
scanf("%d %s %f %f %f", &students[i].id, students[i].name, &students[i].grade[0], &students[i].grade[1], &students[i].grade[2]);
students[i].avg_grade = (students[i].grade[0] + students[i].grade[1] + students[i].grade[2]) / 3;
}
// 计算3门课的总平均成绩
float total_avg_grade = 0;
for (int i = 0; i < n; i++) {
total_avg_grade += students[i].avg_grade;
}
total_avg_grade /= n;
printf("3门课的总平均成绩为:%.2f\n", total_avg_grade);
// 找出平均分最高的学生
int max_index = 0;
for (int i = 1; i < n; i++) {
if (students[i].avg_grade > students[max_index].avg_grade) {
max_index = i;
}
}
printf("平均分最高的学生是:学号%d 姓名%s 成绩:%.2f %.2f %.2f\n",
students[max_index].id, students[max_index].name,
students[max_index].grade[0], students[max_index].grade[1], students[max_index].grade[2]);
free(students);
return 0;
}
```
该程序中,我们定义了一个 `Student` 结构体来存储学生的数据,其中包括学号、姓名、3门课成绩和平均成绩。我们通过动态分配内存来存储所有学生的数据。首先,我们输入每个学生的数据,并计算其平均成绩。然后,我们计算所有学生的平均成绩的平均值来得到3门课的总平均成绩。最后,我们遍历所有学生的数据,找出平均分最高的学生并打印其数据。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)