gpt4 book ai didi

c - 请求用户输入二维数组并将数据存储在 C 数组中

转载 作者:行者123 更新时间:2023-11-30 18:35:09 27 4
gpt4 key购买 nike

我正在编写一个代码来帮助圣诞老人跟踪他在街道上需要的礼物数量,我正在尝试通过使用 2D 数组和嵌套 for 循环来实现这一点,显然这是正确的方法这样做,但在询问第二所房子里的 child 数量后,程序往往会崩溃。代码如下所示:

void distribute_presents()
{
int houses, kids=0;
int KidsInStreet[houses][kids];
int i, j;
printf("Enter the number of houses in the street?\n");
scanf("%d", &houses);
printf("Enter the number of kids in the street?\n");
scanf("%d", &kids);
for (i=0;i<=houses;i++)
{
for (j=0;j<=kids;j++)
{
printf("Enter the number of kids in house %d:\n", i+1, j+1);
scanf("%d", KidsInStreet[i][j]);
}
}
printf("The presents and their respective prices are:\n");
for(i=0;i<=houses;i++)
{
for(j=0;j<=kids;j++)
{
printf("%d", KidsInStreet[i][j]);
}
}
}

最佳答案

我认为您应该首先查询房屋和 child 的数量,然后填充二维数组:

void distribute_presents()
{
int houses, kids = 0;
int i, j;
printf("Enter the number of houses in the street?\n");
scanf("%d", &houses);
printf("Enter the number of kids in the street?\n");
scanf("%d", &kids);
int KidsInStreet[houses][kids];

for (i=0; i < houses; i++)
{
for (j=0; j < kids; j++)
{
printf("Enter the number of kids in house %d:\n", i+1);
scanf("%d", &KidsInStreet[i][j]);
}
}
printf("The presents and their respective prices are:\n");
for (i=0; i < houses; i++)
{
for (j=0; j < kids; j++)
{
printf("%d", &KidsInStreet[i][j]);
}
}
}

关于c - 请求用户输入二维数组并将数据存储在 C 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049598/

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