我正在编写一个基本上有10条街道的代码,并且在每条街道中要求用户提供房屋数量和每座房屋中的孩子数量。但是,当我尝试显示街道工作的数量时,房屋的数量却在显示,而房屋中的孩子数量却没有。我还想知道如何增加街道上的孩子数量,例如一条街道上总共有10个孩子(我真的不知道该怎么做)。我认为问题出在我的for循环中,但是我不确定是什么问题。代码如下所示:
int main()
{
int i=0;
int j=0;
int streets[10];
int houses=0;
int KidsInStreets[houses];
for (i=0;i<10;i++)
{
printf("How many houses are there in street %d:\n", i+1);
scanf("%d",&houses);
for (j=0;j<houses;j++)
{
printf("How many kids are there in house number %d, in street number %d:\n", j+1, i+1);
scanf("%d", &KidsInStreets[j]);
}
}
for (i=0;i<10;i++)
{
for (j=0;j<houses;j++)
{
printf("Street:%d House:%d Kids:%d\n", i+1, j+1, KidsInStreets[j]);//Kids in street output and houses output have bugs, such as all the houses in the street need to be displayed, and the kids thing is just not working
}
}
return 0;
}
最佳答案
一个问题是当您执行houses
时int KidsInStreets[houses];
为零。但是真正的问题是您只有一个阵列,但是每条街道都需要一个阵列。
尝试类似的东西:
int* streets[10]; // Notice *
int houses=0;
for (i=0;i<10;i++)
{
printf("How many houses are there in street %d:\n", i+1);
scanf("%d",&houses);
streets[i] = malloc(houses * sizeof(int)); // Allocate array
for (j=0;j<houses;j++)
{
printf("How many kids are there in house number %d, in street number %d:\n", j+1, i+1);
scanf("%d", &streets[i][j]);
}
}
但是问题是,现在您不知道每条街道上有多少栋房屋。因此,您需要保存该信息。为此,您可以构造一个结构或一个额外的数组。
额外的数组不是那么优雅,但很容易:
int* streets[10]; // Notice *
int houses_in_street[10];
int houses=0;
for (i=0;i<10;i++)
{
printf("How many houses are there in street %d:\n", i+1);
scanf("%d",&houses);
streets[i] = malloc(houses * sizeof(int)); // Allocate array
houses_in_street[i] = houses;
for (j=0;j<houses;j++)
{
printf("How many kids are there in house number %d, in street number %d:\n", j+1, i+1);
scanf("%d", &streets[i][j]);
}
}
for (i=0;i<10;i++)
{
for (j=0;j<houses_in_street[i];j++)
{
printf("Street:%d House:%d Kids:%d\n", i+1, j+1, streets[i][j]);
}
}
更好的解决方案是使用类似以下的结构:
struct street {
int number;
int houses;
int* kids_in_house;
};
// use it like
struct street streets[10];