用结构体和指针编程。某班有5名学生,每名学生的数据包括学号、姓名、3 门课程的成绩。从键盘输入5名学生数据,输出5名同学平均成绩, 以及平均分最高的学生的数据(包括学号、姓名、 3 门课成绩、平均成绩)。
时间: 2023-12-15 15:24:21 浏览: 114
以下是使用结构体和指针编写的代码:
```c
#include <stdio.h>
#define NUM_OF_STUDENTS 5
#define NUM_OF_COURSES 3
struct student {
int id;
char name[20];
int scores[NUM_OF_COURSES];
float avg_score;
};
void input_students(struct student *students, int num);
void calc_avg_score(struct student *students, int num);
struct student *find_highest_avg_score(struct student *students, int num);
int main() {
struct student students[NUM_OF_STUDENTS];
input_students(students, NUM_OF_STUDENTS);
calc_avg_score(students, NUM_OF_STUDENTS);
struct student *highest_avg_score_student = find_highest_avg_score(students, NUM_OF_STUDENTS);
printf("Average score of all students: %.2f\n", students[0].avg_score);
printf("Student with highest average score:\n");
printf("ID: %d\n", highest_avg_score_student->id);
printf("Name: %s\n", highest_avg_score_student->name);
printf("Scores: ");
for (int i = 0; i < NUM_OF_COURSES; i++) {
printf("%d ", highest_avg_score_student->scores[i]);
}
printf("\nAverage score: %.2f\n", highest_avg_score_student->avg_score);
return 0;
}
void input_students(struct student *students, int num) {
for (int i = 0; i < num; i++) {
printf("Enter information for student %d:\n", i + 1);
printf("ID: ");
scanf("%d", &students[i].id);
printf("Name: ");
scanf("%s", students[i].name);
for (int j = 0; j < NUM_OF_COURSES; j++) {
printf("Score for course %d: ", j + 1);
scanf("%d", &students[i].scores[j]);
}
}
}
void calc_avg_score(struct student *students, int num) {
for (int i = 0; i < num; i++) {
float sum = 0;
for (int j = 0; j < NUM_OF_COURSES; j++) {
sum += students[i].scores[j];
}
students[i].avg_score = sum / NUM_OF_COURSES;
}
}
struct student *find_highest_avg_score(struct student *students, int num) {
struct student *highest_avg_score_student = &students[0];
for (int i = 1; i < num; i++) {
if (students[i].avg_score > highest_avg_score_student->avg_score) {
highest_avg_score_student = &students[i];
}
}
return highest_avg_score_student;
}
```
首先定义了一个 `student` 结构体,包含学号、姓名、3门成绩和平均成绩。然后定义了三个函数:
- `input_students`:从键盘输入学生信息。
- `calc_avg_score`:计算每个学生的平均成绩。
- `find_highest_avg_score`:找出平均分最高的学生。
在 `main` 函数中,先调用 `input_students` 和 `calc_avg_score` 函数,然后调用 `find_highest_avg_score` 函数找到平均分最高的学生,最后输出所有学生的平均成绩和平均分最高的学生的信息。
阅读全文