c - 理解 C 中的数组
问题描述
我是 C 新手,需要一些帮助来理解这段代码是如何工作的。我知道它会读取用户写入的值,将它们放入数组中,然后将它们打印出来。
但我不明白为什么我需要两个“计数器”(i
和j
)来做到这一点。有人可以帮我弄清楚吗?
#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]);
}
}
解决方案
您不需要它,您可以简单地重置第一个并重复使用它。但是,您必须仅在使用后才增加索引,否则您将溢出数组的限制:
#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++;
}
}
推荐阅读
- python - TclError:无法识别图像文件“black.gif”中的数据我不明白为什么即使文件类型是 GIF 也会出现错误
- c++ - 您如何在 C 预处理器中使用定义进行逻辑异或
- git - 远程“原点”不支持 LFS 锁定 API //尝试使用 lfs 在 github 中上传超过 100mb 的 model.h5 文件
- scala - Scala SBT 编译挂起(SBT 1.5.0、Scala 2.13.5、Java 11.0.10)
- flutter - 使用 Flutter 从 API 接收数据
- python - 如何将嵌套列表(3D)转换为数组
- sql - SQL Developer 在我创建表时强制大写
- excel - 将路径附加到用户表单选择
- java - ClassCastException 日期范围[]
- reactjs - Laravel,为什么 currentAccessToken()->delete() 在前端未定义,但适用于邮递员?