本文共 1471 字,大约阅读时间需要 4 分钟。
要解决这个问题,我们需要读取n名学生的姓名、学号和成绩,然后分别输出成绩最高和最低的学生的姓名和学号。以下是详细的解决方案:
#include#include #include using namespace std;int main() { int n; cin >> n; vector names(n); vector nums(n); vector scores(n); for (int i = 0; i < n; ++i) { string line; getline(cin, line); size_t first_space = line.find(' '); size_t second_space = line.find(' ', first_space + 1); string name = line.substr(0, first_space); string num = line.substr(first_space + 1, second_space - first_space - 1); string score_str = line.substr(second_space + 1); int score = stoi(score_str); names[i] = name; nums[i] = num; scores[i] = score; } int max_score = scores[0]; int min_score = scores[0]; int max_index = 0; int min_index = 0; for (int i = 1; i < n; ++i) { if (scores[i] > max_score) { max_score = scores[i]; max_index = i; } if (scores[i] < min_score) { min_score = scores[i]; min_index = i; } } cout << names[max_index] << ' ' << nums[max_index] << endl; cout << names[min_index] << ' ' << nums[min_index] << endl; return 0;}
getline
函数来读取每一行数据。find
方法找到字符串中的空格,分割出姓名、学号和成绩。scores
向量中。这种方法高效且直接,能够处理所有符合题目要求的输入情况。
转载地址:http://fceiz.baihongyu.com/