【问题标题】:C++ breaks out of the loop when filling the arrayC++ 在填充数组时跳出循环
【发布时间】:2021-12-30 23:01:41
【问题描述】:

所以基本上我正在尝试创建一个用随机数填充矩阵的循环。我需要使每一列都有不同的范围,对它来说是独一无二的。

    //Variables
    int lsx = 3;
    int lsy = 10;
    int lust[lsy][lsx];
    int i = 0;
    int l = 0;
    int shpp = 7;
    //List setup
    for (i = 0; i < lsy; i++)
    {
        for (l = 0; l < lsx; l++)
        {
            lust[i][l] = 0;
        }
    }
    while (true)
    {
        //List generator
        for (i = 0; i < lsy; i++)
        {
            for (l = 0; l < lsx; l++)
            {
                //Column 1
                if (i == 0)
                {
                    lust[i][l] = rand() % flx;
                    cout << lust[i][l] << '\n';
                }
                //Column 2
                if (i == 1)
                {
                    lust[i][l] = rand() % fly;
                    cout << lust[i][l] << '\n';
                }
                //Column 3
                if (i == 2)
                {
                    lust[i][l] = rand() % shpp;
                    cout << lust[i][l] << '\n';
                }
            }
            cout << "Endline reached! \n \n";
        }
        for (i = 0; i < lsy; i++)
        {
            for (l = 0; l < lsx; l++)
            {
                cout << lust[i][l] << " ";
            }
            cout << "\n";
        }
    }   
}

这只会生成 3 行。有没有人知道为什么会发生这种情况? 我尝试改变一些东西,但只得到了更奇怪的结果,无法完全填充数组This is what the program displays when I try and run it

【问题讨论】:

    标签: c++ for-loop if-statement multidimensional-array while-loop


    【解决方案1】:
    for (l = 0; l < lsx; l++)
        {
        Column 1
        if (i == 0)
        }
        lust[i][l] = rand() % flx;
        cout << lust[i][l] << '\n';
        }
        Column 2
        if (i == 1)
        }
        lust[i][l] = rand() % fly;
        cout << lust[i][l] << '\n';
        }
        Column 3
        if (i == 2)
        {
        lust[i][l] = rand() % shpp;
        cout << lust[i][l] << '\n';
        }
    }
    cout << "Endline reached! \n \n";
    

    您正在使用 i(行迭代器)来评估您要填充的内容。这意味着您的代码将只关注第 0、1 和 2 行。相反,将 i 转换为 l - 您的列迭代器。它应该可以工作。

    另外,请考虑删除 while true 循环。它不仅是多余的,而且考虑到没有中断条件,这也是非常危险的 - 在这种情况下它是安全的,因为你会在附近关闭它,但作为一个好的做法,除非你不能将您的中断条件写为布尔表达式

    【讨论】:

    • 谢谢!它确实解决了手头的问题。它是一个更大程序的一部分,这就是 while 循环存在的原因。我不认为这是问题的一部分,但以防万一
    • 不是,但是 while(true) 总是“有风险的”呵呵。因为它是集成的,所以很好^^
    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 2021-04-21
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 2015-04-22
    相关资源
    最近更新 更多