首页 > 解决方案 > 在c中填充二维数组的第二列

问题描述

我用 [20,25] 范围内的随机数填充第一列,现在我希望用户用 [20,25] 范围内的随机数填充第二列。我怎样才能做到这一点?

#include <stdio.h>

void main()
{
    int Temperature[5][2] = {{20},{21},{22},{23},{24}};

    printf("I created a 2D array of size 5x2,");
    printf("and I filled the first column with random values in the range [20,25]\n");

    for(int i=0; i<5; i++)
    {
        printf("%d ",Temperature[i][0]);
        printf("\n");
    }

    printf("Please fill the second column with values in the range [0,20]\n");

    int i, j;
    for(j=0;j<5;j++)
    {
        printf("Value[%d]:",j);
        scanf("%d", &Temperature[0][j]);
    } 
}

标签: carrays

解决方案


对于 C 中的二维数组,array[x][y] ---> 表示第 xy列

由于数组是 0 索引的,因此示例中的第二列意味着列号应为 1(0 是第一列)

修改后的代码

#include <stdio.h>

void main()
{
    int Temperature[5][2]={{20},{21},{22},{23},{24}};
    printf("I created a 2D array of size 5x2,");
    printf("and I filled the first column with random values in the range [20,25]\n");
    for(int i=0; i<5; i++)
    {
        //correction done here
        printf("%d ",Temperature[i][0]);
        printf("\n");
    }
    printf("Please fill the second column with values in the range [0,20]\n");
    int i, j;
    for(j=0;j<5;j++)
    {
        printf("Value[%d]:",j);
        scanf("%d", &Temperature[j][1]);
    } 
}

推荐阅读