当我们输入8和11时,为什么结果“ eightnine”在一起?

Sat*_*pun 2 c arrays for-loop

当我使用输入8和11运行代码时,输​​出为

eightnine
odd
even
odd
Run Code Online (Sandbox Code Playgroud)

我期望的结果是:

eight
nine
odd
even
Run Code Online (Sandbox Code Playgroud)

为什么八行出现在同一行?循环有问题吗?

#include <stdio.h>
#include <string.h>

int main() {
int a, b;

    scanf("%d\n%d", &a, &b);

    char list[11][5]={"one","two","three","four","five","six","seven","eight","nine","even","odd"};
    int i;
    for (i=a;i<=b;i++)
    {
        printf("%s \n",(i<9?list[i-1]:list[9+i%2]));
    }

     return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 5

您需要char list[11][6],也就是说,您需要5个字符的NUL(用于终止C样式字符串的0)空间。

虽然如此,我还是更喜欢

char* list[] ={"one","two","three","four","five","six","seven","eight","nine","even","odd"};
Run Code Online (Sandbox Code Playgroud)

所有这些问题都消失了。让编译器进行计数!