#include<stdio.h>
#include<stdbool.h>
#define N 20
#define STULEN 5
#define COURSELEN 3
#define SWAP(arr, i, j) { \
struct Student* t = arr[i]; \
arr[i] = arr[j]; \
arr[j] = t; \
}
typedef struct {
int id;
char name[N];
int chinese;
int math;
int english;
}Student;
void course_average(Student* s[], int stulen) {
double sum[COURSELEN] = { 0 };
for (int i = 0; i < COURSELEN; i++) {
for (int j = 0; j < stulen; j++) {
if (i == 0) sum[i] += s[j]->chinese;
else if (i == 1) sum[i] += s[j]->math;
else if (i == 2) sum[i] += s[j]->english;
}
}
for (int i = 0; i < COURSELEN; i++) {
printf("%.2lf ", sum[i] / stulen);
}
printf("\n");
}
int total_score(Student* s) {
return s->chinese + s->math + s->english;
}
void sort_stu(Student* s[], int len) {
//冒泡排序
for (int i = 0; i < len - 1; i++) {
bool flag = true;
for (int j = 0; j < len - i - 1; j++) {
if (total_score(s[j]) < total_score(s[j + 1])) {
flag = false;
SWAP(s, j, j + 1);
}
}
if (flag) break;
}
}
void print_stu(Student* s[], int len) {
for (int i = 0; i < len; i++) {
printf("%d %s %d %d %d\n",
s[i]->id, s[i]->name,
s[i]->chinese, s[i]->math, s[i]->english);
}
printf("\n");
}
int main(void) {
Student stu[STULEN];
for (int i = 0; i < STULEN; i++) {
scanf("%d%s %d%d%d",
&stu[i].id,
stu[i].name,
&stu[i].chinese,
&stu[i].math,
&stu[i].english);
}
//Student* pstu[STULEN] = { stu, stu + 1, stu + 2, stu + 3, stu + 4 };
Student* pstu[STULEN];
for (int i = 0; i < STULEN; i++) {
pstu[i] = &stu[i];
}
sort_stu(pstu, STULEN);
printf("\n");
//最高分学生
printf("The student with the highest score is: ");
print_stu(pstu, 1);
printf("\n");
//课程平均分
printf("The average score for each course is: ");
course_average(pstu, STULEN);
printf("\n");
//排序输出
print_stu(pstu, STULEN);
return 0;
}
/*
1 cat 100 100 100
2 dog 90 91 92
3 frog 57 58 59
4 pig 80 81 82
5 rabbit 85 86 87
*/
【C语言】15_实现学生结构体,求最高分学生 & 课程平均分 & 按总分排序输出
于 2024-05-10 21:41:44 首次发布