五名学生每名学生数据包括学号姓名三门课成绩计算平均值并按平均值排序
时间: 2023-08-12 19:37:31 浏览: 99
好的,以下是用 C 语言实现的代码,您可以参考一下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct {
char id[10]; // 学号
char name[20]; // 姓名
float score[3]; // 三门课成绩
float avg_score; // 平均分
} Student;
// 计算学生平均分
float get_avg_score(Student *student) {
float sum = 0;
for (int i = 0; i < 3; i++) {
sum += student->score[i];
}
return sum / 3;
}
// 按平均分排序
void sort_students(Student students[], int n) {
for (int i = 0; i < n; i++) {
students[i].avg_score = get_avg_score(&students[i]);
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (students[j].avg_score < students[j + 1].avg_score) {
Student temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
}
int main() {
Student students[5] = {
{"001", "张三", {85, 92, 88}, 0},
{"002", "李四", {90, 86, 92}, 0},
{"003", "王五", {80, 78, 85}, 0},
{"004", "赵六", {92, 90, 95}, 0},
{"005", "钱七", {88, 82, 90}, 0}
};
int n = 5;
sort_students(students, n);
for (int i = 0; i < n; i++) {
printf("%s %s %.2f\n", students[i].name, students[i].id, students[i].avg_score);
}
return 0;
}
```
输出结果如下:
```
赵六 004 92.33
李四 002 89.33
张三 001 88.33
钱七 005 86.67
王五 003 81.00
```
希望这个例子能够帮到您!
阅读全文