将整数值存储到二维数组中的程序

program that store integer values into a 2D array

它只是创建随机值

我尝试为数组变量使用单独的值,但我也不知道为什么它从元素 6 开始计数。

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
int array[3][5];

for (i = 0; i<5; i++);
    {
    printf("Input a whole number for row 1 element %d:\n", i+1);
    scanf("%d", &array[0][i]);
    }

printf("Row 1 elements:\n");
for(i = 0; i<5; i++)
{
    printf("%d\n", array[0][i]);
}

return 0;
}

输出:

> Input a whole number for row 1 element 6: 4 Row 1 elements: 0 0 0 0
> 1897665488
> 
> Process returned 0 (0x0)   execution time : 1.969 s Press any key to
> continue.

它从 6 开始计数,因为行 for (i = 0; i < 5; i++); 正在迭代(递增)i 5 次,所以 i 变为 5,然后你打印 i + 1stdout.

所以,基本上你对 printf()scanf() 函数的调用从来都不是任何循环的一部分。

注意:在任何 loop 之后添加 semi-colon ; 意味着没有循环体。基本上这是一个空循环。它对于查找字符串的长度等很有用。

一些提示:

  • 也可以使用头文件 stdlib.h.
  • 中定义的 return EXIT_SUCCESS; 而不是使用裸 return 0;
  • 使用int main(void) { },而不是int main() { }
  • 总是检查scanf()输入是否成功

正确的代码

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int i;
    int array[3][5];

    for (i = 0; i < 5; i++)
    {
        printf("Input a whole number for row 1 element %d:\n", i + 1);
        if (scanf("%d", &array[0][i]) != 1)
        {
            perror("bad input: only numbers are acceptable\n");
            return EXIT_FAILURE;
        }
    }

    printf("Row 1 elements:\n");
    for (i = 0; i < 5; i++)
    {
        printf("%d\n", array[0][i]);
    }

    return EXIT_SUCCESS;
}

输出:

Input a whole number for row 1 element 1:
1
Input a whole number for row 1 element 2:
2
Input a whole number for row 1 element 3:
3
Input a whole number for row 1 element 4:
5
Input a whole number for row 1 element 5:
7
Row 1 elements:
1
2
3
5
7