【C++】1004 成绩排名
读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:
每个测试输入包含 1 个测试用例,格式为第 1 行:正整数 n
第 2 行:第 1 个学生的姓名 学号 成绩
第 3 行:第 2 个学生的姓名 学号 成绩
… … …
第 n+1 行:第 n 个学生的姓名 学号 成绩其中姓名和学号均为不超过 10 个字符的字符串,成绩为 0 到 100 之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。
输出格式:
对每个测试用例输出 2 行,第 1 行是成绩最高学生的姓名和学号,第 2 行是成绩最低学生的姓名和学号,字符串间有 1 空格。输入样例:
3 Joe Math990112 89 Mike CS991301 100 Mary EE990830 95 1 2 3 4输出样例:
Mike CS991301 Joe Math990112
浅析(具体分析看代码)
输入第一行确定了输入的学生数量,将每个学生的成绩与最大最小的成绩进行比较看是否符合最大最小的要求(遍历)。
代码
“暴力美学”求解:
#include
#include
#include
using namespace std;//定义最大、最小的学生姓名、学号、成绩
string max_name, max_id;
string min_name, min_id;
int max_score = 0, min_score = 999;int main() {int n;//定义学生信息string name, id;int score;//输入学生数量cin >> n; //遍历输入学生成绩for (int i = 0; i < n; i++) { cin >> name >> id >> score;//将学生成绩与最大、最小的进行比较if (score > max_score) max_score = score,max_name = name,max_id = id;if (score < min_score) min_score = score,min_name = name, min_id = id;}cout << max_name << " " << max_id << endl;cout << min_name << " " << min_id << endl;return 0;
}
膜拜大佬(结构体):
#include
using namespace std;struct Student{string name;string id;int score;
}student[1000];int main() {ios::sync_with_stdio(false);int n; cin>>n;int max = -1, min = 101, flag1, flag2;for(int i = 0; i < n; i++) {cin>>student[i].name>>student[i].id>>student[i].score;if(max < student[i].score) {max = student[i].score; flag1 = i;}if(min > student[i].score) {min = student[i].score; flag2 = i;}}cout << student[flag1].name << ' ' << student[flag1].id << '\n';cout << student[flag2].name << ' ' << student[flag2].id << '\n';
return 0; }
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
