用C语言编写代码.由键盘任意输入5个学生的姓名、学号、以及每一个学生的4门功课的成绩,分别计算他们的总分和均分,并将此表按总分的高低排序。
时间: 2024-04-29 19:26:24 浏览: 19
好的,我会回答你的问题。以下是用C语言编写的代码,实现输入5个学生的姓名、学号以及每个学生的4门功课成绩,计算总分和均分,并按总分的高低排序。
```c
#include <stdio.h>
#include <string.h>
typedef struct {
char name[20]; // 学生姓名
char id[10]; // 学生学号
int score[4]; // 学生4门课成绩
int sum; // 学生总分
float avg; // 学生平均分
} Student;
void sort(Student *p, int n); // 定义排序函数
int main() {
Student stu[5];
int i, j, sum, n = 5;
// 输入学生信息和成绩
for (i = 0; i < n; i++) {
printf("请输入第%d个学生的姓名、学号和4门课成绩:\n", i+1);
scanf("%s%s%d%d%d%d", stu[i].name, stu[i].id, &stu[i].score[0], &stu[i].score[1], &stu[i].score[2], &stu[i].score[3]);
sum = 0;
for (j = 0; j < 4; j++)
sum += stu[i].score[j];
stu[i].sum = sum;
stu[i].avg = sum / 4.0;
}
// 按总分排序
sort(stu, n);
// 输出结果
printf("\n按总分排序结果如下:\n");
for (i = 0; i < n; i++)
printf("%s %s %d %d %d %d 总分:%d 平均分:%.2f\n", stu[i].name, stu[i].id, stu[i].score[0], stu[i].score[1], stu[i].score[2], stu[i].score[3], stu[i].sum, stu[i].avg);
return 0;
}
// 按总分排序函数
void sort(Student *p, int n) {
int i, j, max, temp;
Student t;
for (i = 0; i < n-1; i++) {
max = i;
for (j = i+1; j < n; j++) {
if (p[j].sum > p[max].sum)
max = j;
}
if (max != i) {
t = p[i];
p[i] = p[max];
p[max] = t;
}
}
}
```
这段代码可以实现输入5个学生的姓名、学号以及每个学生的4门功课成绩,计算总分和均分,并将此表按总分的高低排序。