C++在填充数组时跳出循环
C++ breaks out of the loop when filling the array
所以基本上我是在尝试创建一个用随机数填充矩阵的循环。我需要做到这一点,以便每一列都有不同的范围,并且是独一无二的。
//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
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(true) 除非你不能将你的中断条件写成布尔表达式
所以基本上我是在尝试创建一个用随机数填充矩阵的循环。我需要做到这一点,以便每一列都有不同的范围,并且是独一无二的。
//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
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(true) 除非你不能将你的中断条件写成布尔表达式