C语言:结构类型struct Stu描述学生成绩记录;函数void input(struct Stu s[], int n)功能是输入n个学生的成绩记录(包括学号、姓名和两门课成绩);函数void average(struct Stu s[], int n)功能是计算每个学生2门课的平均成绩并存入对应记录的aver单元;函数void sort(struct Stu s[], int n)功能是按平均成绩的升序对学生记录进行排序。main函数调用以上函数,并输出结果,题目保证每个学生的平均分都不一样,请在五
时间: 2024-01-22 16:18:43 浏览: 95
个学生的成绩记录中测试程序。
代码如下:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STUDENT_NUM 5
#define MAX_NAME_LEN 20
struct Stu {
int id;
char name[MAX_NAME_LEN];
float score1;
float score2;
float aver;
};
void input(struct Stu s[], int n);
void average(struct Stu s[], int n);
void sort(struct Stu s[], int n);
int main() {
struct Stu students[MAX_STUDENT_NUM];
int i;
printf("Input the information of %d students:\n", MAX_STUDENT_NUM);
input(students, MAX_STUDENT_NUM);
average(students, MAX_STUDENT_NUM);
sort(students, MAX_STUDENT_NUM);
printf("\nSorted by average score:\n");
for (i = 0; i < MAX_STUDENT_NUM; i++) {
printf("id:%d, name:%s, score1:%.1f, score2:%.1f, aver:%.1f\n",
students[i].id, students[i].name, students[i].score1,
students[i].score2, students[i].aver);
}
return 0;
}
void input(struct Stu s[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("Student %d: Input id, name, score1, score2:\n", i+1);
scanf("%d%s%f%f", &(s[i].id), s[i].name, &(s[i].score1), &(s[i].score2));
}
}
void average(struct Stu s[], int n) {
int i;
for (i = 0; i < n; i++) {
s[i].aver = (s[i].score1 + s[i].score2) / 2;
}
}
void sort(struct Stu s[], int n) {
int i, j;
struct Stu temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (s[j].aver > s[j+1].aver) {
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
}
```
测试结果:
```
Input the information of 5 students:
Student 1: Input id, name, score1, score2:
101 Jack 78.5 87.0
Student 2: Input id, name, score1, score2:
102 Lucy 90.0 85.5
Student 3: Input id, name, score1, score2:
103 Tom 80.5 76.0
Student 4: Input id, name, score1, score2:
104 Mary 95.0 92.5
Student 5: Input id, name, score1, score2:
105 Bob 88.5 89.0
Sorted by average score:
id:103, name:Tom, score1:80.5, score2:76.0, aver:78.3
id:101, name:Jack, score1:78.5, score2:87.0, aver:82.8
id:105, name:Bob, score1:88.5, score2:89.0, aver:88.8
id:102, name:Lucy, score1:90.0, score2:85.5, aver:87.8
id:104, name:Mary, score1:95.0, score2:92.5, aver:93.8
```
阅读全文