80求助:下载数据后得知,有一组数据的输出多处一行

P1093 [NOIP2007 普及组] 奖学金

uuuuuuu000 @ 2024-04-25 00:04:59

#include<iostream>
using namespace std;

struct stu
{
    int c, m, e;
    int num;
};

int sum_s(stu student)
{
    int sum = student.c + student.m + student.e;
    return sum;
}

void swap_s(stu& stu1, stu &stu2)
{
    stu t;
    t = stu1;
    stu1 = stu2;
    stu2 = t;
}

void ord_s(stu student[300], int n)
{
    int sum1, sum2;
    for (int i = 0; i < n; i++)
    {
        sum1 = sum_s(student[i]);
        for (int j = i + 1; j < n; j++)
        {
            sum2 = sum_s(student[j]);
            if (sum2 == sum1)
            {
                if (student[i].c < student[j].c)
                {
                    swap_s(student[i], student[j]);
                }
                else
                {
                    if (student[i].c == student[j].c)
                    {
                        if (student[i].num > student[j].num)
                        {
                            swap_s(student[i], student[j]);
                        }
                    }
                }
            }
            if (sum2 > sum1)
            {
                swap_s(student[i], student[j]);
                sum1 = sum2;
            }
        }
    }
    return;
}

int main()
{
    int n;
    while (cin >> n)
    {
        stu student[300];
        for (int i = 0; i < n; i++)
        {
            cin >> student[i].c >> student[i].m >> student[i].e;
            student[i].num = i + 1;
        }
        ord_s(student, n);
        for (int i = 0; i < 5; i++)
        {
            cout << student[i].num << " " << sum_s(student[i]) << endl;
        }
    }
    return 0;
}

by uuuuuuu000 @ 2024-04-25 00:05:38

80求助 下载数据后得知,有一组数据的输出多处一行,但是看不出来哪里有错


by xyjstud @ 2024-04-25 12:59:47

@uuuuuuu000
看不出来为什么,但有两个解决方法,一个是把for (int i = 0; i < n; i++)换成
for (int i = 0; i <= n; i++),还有一个办法是直接cin>>n,不要while了,具体为啥我也不知道,我本地跑的时候,他反正是多做了一次没必要的while循环,最后一行数据还没读进来答案就被输出了,要是知道为啥了记得@我一下hh


|