有5个学生的信息,包括学号(整数),姓名(字符数组),和5门课的成绩(整型数组),请按照总成绩从低到高排序,若总成绩相同则按照学号从小到大排序。之后输出排序后的结果,注意要输出所有学生的信息,包括总成绩。C++
时间: 2024-03-14 12:44:58 浏览: 19
好的,这道题目可以使用结构体和快速排序来解决。具体实现如下:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
// 定义学生结构体
struct Student {
int id; // 学号
char name[20]; // 姓名
int score[5]; // 5门课成绩
int total_score; // 总成绩
};
// 定义比较函数,先按照总成绩从低到高排序,若总成绩相同则按照学号从小到大排序
bool cmp(Student a, Student b) {
if (a.total_score == b.total_score) {
return a.id < b.id;
}
return a.total_score < b.total_score;
}
int main() {
// 输入5个学生的信息
Student students[5];
for (int i = 0; i < 5; i++) {
cout << "请输入第" << i+1 << "个学生的信息(学号 姓名 5门课成绩):" << endl;
cin >> students[i].id >> students[i].name;
for (int j = 0; j < 5; j++) {
cin >> students[i].score[j];
}
// 计算总成绩
students[i].total_score = 0;
for (int j = 0; j < 5; j++) {
students[i].total_score += students[i].score[j];
}
}
// 对学生信息进行排序
sort(students, students+5, cmp);
// 输出排序后的结果
for (int i = 0; i < 5; i++) {
cout << "学号:" << students[i].id << " 姓名:" << students[i].name << " 总成绩:" << students[i].total_score << endl;
}
return 0;
}
```
输入样例:
```
请输入第1个学生的信息(学号 姓名 5门课成绩):
1001 Tom 90 80 70 85 95
请输入第2个学生的信息(学号 姓名 5门课成绩):
1002 Jerry 80 85 90 75 95
请输入第3个学生的信息(学号 姓名 5门课成绩):
1003 Lucy 70 75 80 65 95
请输入第4个学生的信息(学号 姓名 5门课成绩):
1004 Lily 85 90 95 80 75
请输入第5个学生的信息(学号 姓名 5门课成绩):
1005 Bob 90 85 80 75 70
```
输出样例:
```
学号:1003 姓名:Lucy 总成绩:385
学号:1002 姓名:Jerry 总成绩:425
学号:1001 姓名:Tom 总成绩:420
学号:1004 姓名:Lily 总成绩:425
学号:1005 姓名:Bob 总成绩:400
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)