可以请教一下dl们个问题吗?

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

Langrange2021 @ 2022-09-17 18:20:46

这是我第一遍没有过的代码,用了循环遍历字符数组赋值,然而没有过。

#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;
}

这是我第二遍用c语言strcpy函数改对的代码,ac全过

#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;
            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;
}

有没有dl可以解释一下循环遍历数组为什么不对吗?


by comcopy @ 2022-09-17 18:24:09

循环遍历没有把终止符算进去

字符数组单个输入的话是不会添加终止符的,所以最后输出的时候会莫名多几个空字符的亚子。。。


by comcopy @ 2022-09-17 18:24:38

@Langrange2021 至少我把中间的if删掉就对了((


by Langrange2021 @ 2022-09-17 21:33:52

@comcopy 啊竟然是这样,那么也就是说这里要移动字符串最好是用strcpy函数吗?


by comcopy @ 2022-09-17 21:48:55

@Langrange2021 有意识地添加终止符号


by Langrange2021 @ 2022-09-17 22:02:46

@comcopy 谢谢dl


|