如何将值添加到数组而不在 for 循环外将它们重置为 0
How do I add values to an array without them resetting to 0 outside the for loop
我正在尝试编写将 3 项添加到数组的代码,然后查找任何对。然而,当 for 循环结束时,数组只是重置为 {0,0,0}。我如何 "save" 数组值以便它们在退出循环后不重置?
srand(seed);
const int RANDOMS_NEEDED = 3;
int rando = 0;
int rando_max = 10;
int slotsOutput[3] = {};
cout << "\t Generating random numbers from 0 to " << rando_max << endl << "\t";
for (int i = 0; i < RANDOMS_NEEDED; i++) {
int slotsOutput[3] = {};
rando = rand();
int randoInRange = rando % (rando_max + 1);
cout << "| " << randoInRange << " |";
slotsOutput[i] = randoInRange;
Sleep(500);
cout << slotsOutput[i];
}
How do I "save" the array values so they dont reset after exiting the loop?
您需要删除在循环内重置数组的代码 - 它应该已经在循环外完成。
for (int i = 0; i < RANDOMS_NEEDED; i++) {
int slotsOutput[3] = {}; //<-- remove
在for循环内,声明一个新数组slotsOutput,与循环外的变量同名。循环内的操作只影响第二个数组,它通过具有相同的名称隐藏第一个数组。当循环退出时,第二个数组消失,您可以访问第一个数组,它没有改变。
如果您启用了适当的警告级别,您的编译器应该对此发出警告。
在for
循环中,你是shadowing你预先声明的变量slotsOutPut
。
int slotsOutput[3] = {}; // Declares here
...
for (int i = 0; i < RANDOMS_NEEDED; i++) {
int slotsOutput[3] = {}; // Declared again, which shadows above slotsOutPut
你所做的只是简单的。
int asdf = 3; // asdf is 3 here
{
int asdf = 4; // asdf is 4 here, but it's different asdf to above one.
cout << asdf; // prints 4
} // local variable asdf is gone with the end of the scope.
cout << asdf; // prints 3
看来您必须删除 for
循环中的行 int slotsOutput[3] = {};
。
我正在尝试编写将 3 项添加到数组的代码,然后查找任何对。然而,当 for 循环结束时,数组只是重置为 {0,0,0}。我如何 "save" 数组值以便它们在退出循环后不重置?
srand(seed);
const int RANDOMS_NEEDED = 3;
int rando = 0;
int rando_max = 10;
int slotsOutput[3] = {};
cout << "\t Generating random numbers from 0 to " << rando_max << endl << "\t";
for (int i = 0; i < RANDOMS_NEEDED; i++) {
int slotsOutput[3] = {};
rando = rand();
int randoInRange = rando % (rando_max + 1);
cout << "| " << randoInRange << " |";
slotsOutput[i] = randoInRange;
Sleep(500);
cout << slotsOutput[i];
}
How do I "save" the array values so they dont reset after exiting the loop?
您需要删除在循环内重置数组的代码 - 它应该已经在循环外完成。
for (int i = 0; i < RANDOMS_NEEDED; i++) {
int slotsOutput[3] = {}; //<-- remove
在for循环内,声明一个新数组slotsOutput,与循环外的变量同名。循环内的操作只影响第二个数组,它通过具有相同的名称隐藏第一个数组。当循环退出时,第二个数组消失,您可以访问第一个数组,它没有改变。
如果您启用了适当的警告级别,您的编译器应该对此发出警告。
在for
循环中,你是shadowing你预先声明的变量slotsOutPut
。
int slotsOutput[3] = {}; // Declares here
...
for (int i = 0; i < RANDOMS_NEEDED; i++) {
int slotsOutput[3] = {}; // Declared again, which shadows above slotsOutPut
你所做的只是简单的。
int asdf = 3; // asdf is 3 here
{
int asdf = 4; // asdf is 4 here, but it's different asdf to above one.
cout << asdf; // prints 4
} // local variable asdf is gone with the end of the scope.
cout << asdf; // prints 3
看来您必须删除 for
循环中的行 int slotsOutput[3] = {};
。