有dl可以看一下吗?

P5740 【深基7.例9】最厉害的学生

Langrange2021 @ 2022-09-17 17:43:53

#include <stdio.h>
#include <string.h>
struct test
{
    char name[9];
    int chin;
    int math;
    int eng;
};
int main()
{
    int max = -1;
    int N;
    scanf("%d", &N);
    char na[9];
    int ch = 0;
    int ma = 0;
    int en = 0;
    for (int k = 0; k < N; k++)
    {
        struct test store;
        int sum;
        scanf("%s", store.name);
        scanf("%d%d%d", &store.chin, &store.math, &store.eng);
        sum = store.chin + store.math + store.eng;
        if (sum > max)
        {
            max = sum;
            for (int q = 0; q < 9; q++)
            {
                if (store.name[q] == '\0')
                {
                    break;
                }
                na[q] = store.name[q];
            }
            ch = store.chin;
            ma = store.math;
            en = store.eng;
        }
    }
    for (int y = 0; y < 9; y++)
    {
        if (na[y] == '\0')
        {
            break;
        }
        printf("%c", na[y]);
    }
    printf(" ");
    printf("%d %d %d", ch, ma, en);
    return 0;
}

by Mr_Gengar @ 2022-09-17 18:00:52

#include <stdio.h>
#include <string.h>
struct test
{
    char name[9];
    int chin;
    int math;
    int eng;
};

char na[9];
int n, max=-1, ch, ma, en;
int main()
{
    scanf("%d", &n);
    for (int k = 0; k < n; k++)
    {
        struct test store;
        int sum;
        scanf("%s", store.name);
        scanf("%d%d%d", &store.chin, &store.math, &store.eng);
        sum = store.chin + store.math + store.eng;
        if (sum > max)
        {
            max = sum;
            strcpy(na, store.name);
            ch = store.chin;
            ma = store.math;
            en = store.eng;
        }
    }
    printf("%s ", na);
    printf("%d %d %d", ch, ma, en);
    return 0;
}

推测是因为na末尾会有残余数据导致WA


by Mr_Gengar @ 2022-09-17 18:01:12

@Langrange2021


by Langrange2021 @ 2022-09-17 18:14:22

@Infi_nut 我过了,谢谢dl。我可以请教一下吗? 为什么我的那种用循环输出的方法不对,用strcpy函数就对了呢?


by ud2_ @ 2022-09-17 18:22:23

@Langrange2021

if (store.name[q] == '\0')
{
    break;
}

复制字符串时没把 0 一同复制过去,输出时就越界了。


by Mr_Gengar @ 2022-09-17 18:39:39

@ud2_ 正解


|