在 C 中用 scanf 填充数组(需要打印最后 5 个输入的数字)

Fill array with scanf in C (last 5 entered numbers need to be printed)

我遇到 school-assignment 的问题,如下所示:

"write a program that'll repeatedly ask a user for a number and if the user's input is 0, and the loop ends, print the last 5 numbers in an array. If there are less than 5 scanned numbers, the unused values must be 0"

它应该看起来像这样:

这是我的代码:

int main()
{
int i, array[4] = {};

while(1)
{
    printf("Next number: <0 = quit>: ");
    scanf("%i", &i);

    if(i!=0)
    {
        array[0] = array[1];
        array[1] = array[2];
        array[2] = array[3];
        array[3] = array[4];
        array[4] = i;
    }

    else
        break;
}

for(i=0; i<=4; i++)
{
    printf("Number %i is: %i\n", i+1, array[i]);
}

return 0;
}

但是当我打印数字时,最后一个数字 ( array[4] ) 是 0.

我做错了什么?

您在这里声明了一个长度为 4 的数组:

int i, array[4] = {};

此数组的索引将从 0 到 3,因此您永远不要尝试访问 array[4],这将导致未定义的行为