C++ 成绩排名
读入 n(>)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:
每个测试输入包含 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
输出样例:
Mike CS991301
Joe Math990112
1 #include <iostream>
2 #include <vector>
3 #include <string>
4 #include <cstdlib>
5 #include <algorithm>
6
7
8 using namespace std;
9
10 struct Student
11 {
12 string name;
13 string id;
14 int score;
15 };
16 bool cmp(Student &s1,Student &s2)
17 {
18 return s1.score > s2.score;
19 }
20
21 int main()
22 {
23 int line;
24 string input;
25 cin >> line;
26 vector<Student> students;
27 for(int i = 0; i < line;++i)
28 { Student stu;
29 for(int j = 0; j < 3;++j)
30 {
31 cin >> input;
32 if(j == 0)
33 {
34 stu.name = input;
35 }else if(j == 1){
36 stu.id = input;
37 }else if(j == 2)
38 {
39 stu.score = atoi(input.c_str());
40 }
41 }
42 students.push_back(stu);
43 }
44 sort(students.begin(),students.end(),cmp);
45 cout << students[0].name << " " << students[0].id << endl
46 << students[line-1].name << " " << students[line-1].id << endl;
47
48
49 return 0;
50 }
一开始想用getline是一次性接收一行数据,但是觉得太麻烦了,况且每一个数据刚好都是以空格分隔开的,所以就直接用了cin。cin只能接收空格前的,例如:hello world 只能接收到hello。
这样就直接两个循环,外层循环行,内层循环每行的数据。
不过有一个地方比较棘手,我cin输入接收类型是string的,但是呢成绩是double,因此要用转换类型的函数,我查资料得到两个函数。
一个是我上文用的int atoi(const char *str)。这个函数是c函数,导入文件是#include<cstdlib>
另一个是stoi函数,定义:stoi(字符串,起始位置,n进制),将 n 进制的字符串转化为十进制,导入文件是#include<string>
当然是第二种更好,但是我的codeblocks总是报错,于是就用了上文的atoi,如果可编译的话第二种是首选。
posted on 2020-04-17 21:28 秃头女孩今夜也不睡觉 阅读(1074) 评论(1) 编辑 收藏 举报