要求用户输入二维数组并将数据存储在C中 [英] Asking for user input for a 2d array and storing the data in the array in C

查看:183
本文介绍了要求用户输入二维数组并将数据存储在C中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a code to help Santa track the number of presents he needs for a street, and I am trying to do it through the use for a 2D array, and nested for loops, and apparently this is the right way of doing it, but the program tends to crash after asking for the number of kids in the second house. the code is shown below:

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]);
    }
}
}


推荐答案

我认为您应该先 先查询房屋和孩子的数量,然后填充2D数组:

I think you should query for the number of houses and kids first, then populate the 2D array:

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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆