首页 > 解决方案 > 理解 C 中的数组

问题描述

我是 C 新手,需要一些帮助来理解这段代码是如何工作的。我知道它会读取用户写入的值,将它们放入数组中,然后将它们打印出来。

但我不明白为什么我需要两个“计数器”(ij)来做到这一点。有人可以帮我弄清楚吗?

#include<stdio.h>
int main ()
{                               
int A[5];
int i=0;
int j=0;

while (i < 5)                
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}

while (j < 5)               
{
j++;
    printf ("\n%d\n", A[j]);
}
}

标签: c

解决方案


您不需要它,您可以简单地重置第一个并重复使用它。但是,您必须仅在使用后才增加索引,否则您将溢出数组的限制:

#include<stdio.h>
int main ()
{                               
    int A[5];
    int i=0;


    while (i < 5) {               
        printf("Enter your %d number\n", i);
        scanf("%d", &A[i]); // the last must be 4 not 5
        i++;                //<== increment here
    }

    i=0;
    while (i < 5)               
    {
        printf ("\n%d\n", A[i]); //idem
        i++;
    }
}

推荐阅读