我写了一个包含 10 个数字的数组的小程序,我希望程序的输出看起来像这样:
Index Value 0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 16 8 18 9 20
However I do not know how to make my code do that. This is my code
#include<stdio.h>
int main()
{
int a[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; // 10 elements
int i;
for(i=0; i<(&a)[1]-a; i++)
printf("%d ", a[i]);
printf("\n\n");
return 0;
}
最佳答案
(&a)[1]-a
语法不好,也不是您想在此处执行的操作。我相信这会得到 a
的地址,加 1,然后减去 a
的地址,所以你最终会得到值 1。这将使你的 for
循环只运行一次。您希望它运行与数组中的值一样多的次数,以便它打印其中的每个值。
为数组的长度创建一个全局常量,并使用它。我使用了 LEN
。
#include<stdio.h>
#define LEN 10
int main()
{
int a[LEN] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; // 10 elements
int i;
// Header
printf("Index\tValue");
for(i = 0; i < LEN; i++)
printf("%d\t%d\n", i, a[i]); // `\n` newline to print next values on next line
printf("\n\n");
return 0;
}
关于c - 编写一个程序,使用 for 循环遍历此数组,显示存储在每个索引处的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57170891/