C++ 如果它运行超过11次程序迭代,为什么会进入无限循环?
在我将for循环I更改为I=0之前,程序就像一个符咒一样工作;我想让它成为员工;我++ 如果我超过10,出于某种原因,它会进入一个无限循环,我不知道为什么。 我需要22次迭代,或者更具体地说,员工数量C++ 如果它运行超过11次程序迭代,为什么会进入无限循环?,c++,infinite-loop,C++,Infinite Loop,在我将for循环I更改为I=0之前,程序就像一个符咒一样工作;我想让它成为员工;我++ 如果我超过10,出于某种原因,它会进入一个无限循环,我不知道为什么。 我需要22次迭代,或者更具体地说,员工数量 int main() { string pairs[22][22] = { { "Mo", "Filippo", "AJ", "Zac", "Alex", "Brandon", "Alec", "Devon", "Anita", "Ariel", "Shannon", "Matt",
int main()
{
string pairs[22][22] =
{
{ "Mo", "Filippo", "AJ", "Zac", "Alex", "Brandon", "Alec", "Devon", "Anita", "Ariel", "Shannon", "Matt", "Reid", "Connor", "Austin", "Alan", "Chelsea", "Michelle", "Taylor", "Spencer", "Laura", "Marcos" }
};
int employees = 22;
int paired;
int randNum;
bool alreadyPaired;
bool stopCounter;
//If this is i < 11 or anything higher it will go in an infinite loop
for (int i = 0; i < 10; i++)
{
paired = 0;
while (paired != employees)
{
do
{
randNum = rand() % employees;
} while (pairs[0][randNum] == pairs[0][i]);
alreadyPaired = false;
for (int a = 1; a < employees; a++)
{
if (pairs[a][i] == pairs[0][randNum])
{
alreadyPaired = true;
}
}
if (alreadyPaired != true)
{
int counter2 = 1;
stopCounter = false;
while (counter2 < employees && stopCounter != true)
{
if (pairs[counter2][i] == "" && pairs[counter2][randNum] == "")
{
stopCounter = true;
}
else
{
counter2++;
}
}
if (counter2 < employees)
{
pairs[counter2][i] = pairs[0][randNum];
pairs[counter2][randNum] = pairs[0][i];
}
}
paired = 0;
for (int a = 0; a < employees; a++)
{
if (pairs[a][i] != "")
{
paired++;
}
}
}
}
for (int i = 0; i < employees; i++)
{
for (int j = 0; j < employees; j++)
{
cout << pairs[j][i] << " ";
}
cout << "\n\n";
}
return 0;
}
intmain()
{
串对[22][22]=
{
{“Mo”、“Filippo”、“AJ”、“Zac”、“Alex”、“Brandon”、“Alec”、“Devon”、“Anita”、“Ariel”、“Shannon”、“Matt”、“Reid”、“Connor”、“Austin”、“Alan”、“Chelsea”、“Michelle”、“Taylor”、“Spencer”、“Laura”、“Marcos”}
};
国际雇员=22;
整数对;
int-randNum;
布勒已经准备好了;
布尔计数器;
//如果这是i<11或更高,它将进入一个无限循环
对于(int i=0;i<10;i++)
{
配对=0;
while(配对!=员工)
{
做
{
randNum=rand()%员工;
}而(pairs[0][randNum]==pairs[0][i]);
alreadyPaired=假;
对于(int a=1;a cout首先,检查Knuth的洗牌算法(它将帮助您分配)
乍一看,您在尝试从1到小于22配对时遇到了问题。
您将在21(或20,因为21不能配对)而不是22中“解决”问题
算法本身将2个实体配对,这意味着所需的i增量应为11(22/2)。
但是,最后一个循环(i=11)无法完成,因为程序的一部分只考虑21/2=10个实体
你的程序应该进入无限循环no,即使你放了8个雇员,使i上升到4
我无法准确指出您在代码中犯了这个错误的确切位置,但根据经验,从1而不是0启动计数器时要非常小心。该程序就像一个符咒一样工作,直到我更改for循环
,然后不要更改for循环。我看不到任何明显的错误。当您通过它时会发生什么?@clcto我猜是UB,它甚至可以关闭你的冰箱。。。