我正在编写一个使用2D数组来存储房屋号码和房子中孩子数量的代码,但是我对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=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;
}
答案 0 :(得分: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]);
}
}