gpt4 book ai didi

c - 在 C 中写入数组的数组并显示数组的数组中的单独实体

转载 作者:行者123 更新时间:2023-11-30 14:51:43 25 4
gpt4 key购买 nike

我正在编写一个基本上有 10 条街道的代码,在每条街道中,用户都会被要求提供房屋数量以及每间房屋中的 child 数量。但是,当我尝试显示街道数量时,房屋数量有效,但房屋中的 child 数量却不起作用。我还想知道如何添加街道上 child 的数量,例如街道 1 总共有 10 个 child (我真的不知道如何执行这部分)。我认为问题出在我的 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;

}

最佳答案

一个问题是,当您执行 int KidsInStreets[houses]; 时,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];

关于c - 在 C 中写入数组的数组并显示数组的数组中的单独实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48065088/

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