1004 成绩排名 (20分)
发布日期:2021-05-12 05:58:50 浏览次数:11 分类:精选文章

本文共 1471 字,大约阅读时间需要 4 分钟。

要解决这个问题,我们需要读取n名学生的姓名、学号和成绩,然后分别输出成绩最高和最低的学生的姓名和学号。以下是详细的解决方案:

方法思路

  • 读取输入:首先读取输入的学生数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;}

    代码解释

  • 读取输入:首先读取n的值,然后循环读取每一行信息。使用getline函数来读取每一行数据。
  • 分割姓名、学号和成绩:使用find方法找到字符串中的空格,分割出姓名、学号和成绩。
  • 转换成绩:将成绩字符串转换为整数,存储到scores向量中。
  • 寻找最高分和最低分:遍历成绩向量,记录最高分和最低分对应的学生索引。
  • 输出结果:根据记录的索引,分别输出最高分和最低分学生的姓名和学号。
  • 这种方法高效且直接,能够处理所有符合题目要求的输入情况。

    上一篇:【PTA】计算职工工资 (15分)
    下一篇:1002 写出这个数 (20分)

    发表评论

    最新留言

    关注你微信了!
    [***.104.42.241]2025年04月18日 07时35分10秒