gpt4 book ai didi

在 C 中创建、存储和输出二维数组

转载 作者:行者123 更新时间:2023-11-30 20:32:17 26 4
gpt4 key购买 nike

我正在编写一个代码,使用二维数组来存储门牌号和房子里的 child 数量,但我在 for 循环方面遇到了一些问题,而且我不太明白问题是什么。数组的维度是房屋的数量即列数(这是用户输入),并且只有两行作为 child 的数量由用户输入到第二行。代码如下所示:

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

int main()
{
int i=0;
int j=0;
int houses=0;
int kids=0;
printf("How many houses are there in the street?\n");
scanf("%d", &houses);
int KidsInStreet[houses][2];//Columns are the houses and the rows are
the number of kids
for(i=0;i<houses;i++)
{
for(j=0;j<2;j++)
{
printf("Enter the value for KidsInStreet[%d][%d]:\n", i, j);
scanf("%d", &KidsInStreet[i][j]);
}
}
for (i=0;i<houses;i++)
{
for(j=0;j<2;j++)
{
printf("House number:%d. Number of kid(s):%d\n", KidsInStreet[i]
[j]);
}
}


return 0;
}

最佳答案

如果我很好地理解了这个要求,你就不需要 2 个 for 循环。所以你的代码如下:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0;
int j=0;
int houses=0;
int kids=0;
printf("How many houses are there in the street?\n");
scanf("%d", &houses);
int KidsInStreet[houses][2];//Columns are the houses and the rows are the number of kids

for(i = 1; i <= houses; i++)
{
KidsInStreet [i][1] = i;
printf("Enter the value for KidsInStreet[%d]:\n", i);
scanf("%d", &KidsInStreet[i][2]);
}

for (i = 1; i <= houses; i++)
{
printf("House number:%d. Number of kid(s):%d\n", KidsInStreet[i][1], KidsInStreet[i][2]);
}



}

关于在 C 中创建、存储和输出二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053452/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com