编写C语言程序:有5个结构体变量,内含学生学号、姓名和3门课程的成绩。要求输出平均成绩最高的学生的信息(包括学号、姓名、3门课程成绩和平均成绩)。要求用结构体变量和结构体变量的指针作函数参数。
时间: 2024-04-21 15:26:38 浏览: 103
下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_OF_STUDENTS 5
#define NUM_OF_COURSES 3
typedef struct {
int id;
char name[20];
float grades[NUM_OF_COURSES];
float avg;
} Student;
void calc_avg(Student* s) {
float sum = 0;
for (int i = 0; i < NUM_OF_COURSES; i++) {
sum += s->grades[i];
}
s->avg = sum / NUM_OF_COURSES;
}
void print_student(const Student* s) {
printf("ID: %d\n", s->id);
printf("Name: %s\n", s->name);
printf("Grades: %.1f %.1f %.1f\n", s->grades[0], s->grades[1], s->grades[2]);
printf("Average: %.1f\n", s->avg);
}
void print_highest_avg(Student* students, int n) {
Student* highest_student = &students[0];
for (int i = 1; i < n; i++) {
calc_avg(&students[i]);
if (students[i].avg > highest_student->avg) {
highest_student = &students[i];
}
}
printf("The student with the highest average is:\n");
print_student(highest_student);
}
int main() {
Student students[NUM_OF_STUDENTS] = {
{20210001, "Tom", {85, 92, 88}},
{20210002, "Jerry", {90, 87, 92}},
{20210003, "Alice", {79, 85, 92}},
{20210004, "Bob", {92, 90, 88}},
{20210005, "Eve", {88, 89, 90}}
};
print_highest_avg(students, NUM_OF_STUDENTS);
return 0;
}
```
程序中定义了一个 `Student` 结构体,包含学生的学号、姓名、3门课程的成绩和平均成绩。`calc_avg` 函数用于计算学生的平均成绩,`print_student` 函数用于输出学生的信息,`print_highest_avg` 函数用于输出平均成绩最高的学生的信息。在 `main` 函数中,定义了 5 个学生结构体,并调用了 `print_highest_avg` 函数来输出平均成绩最高的学生的信息。
阅读全文