PAT 1004(成绩排名)(C++)

本题主要掌握对字符串的基本知识,例如输入格式,输出格式还有一些函数

题目:读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。

C++代码

#include<iostream>
#include<string>
using namespace std;
//学生的结构体,也可以用类更方便
struct student
{
    string name ;
    string  number ;
    int score;
}stu[100000];
int main()
{
    int n = 0;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> stu[i].name >> stu[i].number >> stu[i].score;
        //判断是否符合输入格式,不符合一直循环
        while (stu[i].name.length() >10 || stu[i].number.length() > 10 || stu[i].score < 0 || stu[i].score>100)
        {
            cin >> stu[i].name >> stu[i].number >> stu[i].score;
        }
    }
    int index_max = 0, index_min = 0;
    int max_score = 0, min_score = 0;
    int k = 0;
    //提取最大最小分数所在的下标
    while (n--)
    {
        if (max_score <= stu[k].score)
        {
            max_score = stu[k].score;
            index_max = k;
        }
        if (min_score>=stu[k].score)
        {
            min_score = stu[k].score;
            index_min = k;
        }
        k++;
    }
    cout << stu[index_max].name << " " << stu[index_max].number << endl;
    cout << stu[index_min].name << " " << stu[index_min].number << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zongji/p/12218516.html