C++选择排序算法:找出班级学习小状元 (不使用vector)
以下是使用选择排序算法来解答的C++代码,不使用vector头文件:
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int math;
int chinese;
int english;
int geography;
int total;
};
void selectionSort(Student students[], int n) {
for (int i = 0; i < n - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < n; j++) {
if (students[j].total > students[maxIndex].total) {
maxIndex = j;
}
}
swap(students[i], students[maxIndex]);
}
}
int main() {
int n;
cin >> n;
Student students[n];
for (int i = 0; i < n; i++) {
cin >> students[i].name >> students[i].math >> students[i].chinese >> students[i].english >> students[i].geography;
students[i].total = students[i].math + students[i].chinese + students[i].english + students[i].geography;
}
selectionSort(students, n);
for (int i = 0; i < n; i++) {
cout << students[i].total << endl;
}
cout << students[0].name << endl;
cout << students[0].math << ' ' << students[n-1].geography << endl;
return 0;
}
请注意,该代码使用了结构体来存储学生的信息,并使用选择排序算法对学生按总分进行排序。最后输出每位同学的总分、总分最高的那位同学的姓名,以及所有成绩中最高的分数和最小的分数。
问题描述:
小明同学所在的班级共有N名同学,期末考试时进行了数学、语文、英语、地理四门功课的测试。现要将班里总分最高的同学评为'学习小状元'。
例如:
如3名学生,4门课程的成绩如下:
image.png
请同学们帮助计算:
(1) 每位同学的总分是多少?
(2) 找出总分最高的那位同学。
(3) 找出所有成绩中最高的分数和最小的分数。
输入描述:
第一行:有一个整数N,表示有N名同学(已知1≤N≤30 )。
后N行:每两行代表一个人的信息记录:包括学生的姓名及4门功课的分数:其中分数为整数,每个分数互不相同(不需判断),各数据之间空1个格。
输出描述:
前N行:每行一个数据是每位同学的总分;
第N+1行:是总分最高的那位同学的姓名;
第N+2行:是所有成绩中最高的分数和最小的分数(空1个格)
要求:
每一行的数据都从第一列开始输出。
用例输入 1
3
hong 98 90 87 74 ming 96 92 85 97 zhang 95 78 56 91
用例输出 1
349 370 320 ming 98 56
原文地址: https://www.cveoy.top/t/topic/pEP6 著作权归作者所有。请勿转载和采集!