为什么我的循环没有重新启动到第一次迭代?C++



我正在用C++制作骰子游戏。我想知道为什么它不重新启动循环。这场比赛是三局三胜制。只要玩家想继续玩,它就应该重新开始循环。但是,它只重新启动循环一次。第二次按"Y"或"是"时,它就退出了程序。

我试过将重新启动放在嵌套的while循环中,但似乎也不起作用。

restart:    
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;

cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;
if (cDice1 > pDice1) {
cout << "Computer wins!" << endl << endl;
cWin++;
} if (pDice1 > cDice1) {
cout << "Player wins!" << endl << endl;
pWin++;
} if (pDice1 == cDice1) {
cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
cout << "Player wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}if (cWin > pWin) {
cout << "Computer wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}


}

首先,这是您的全部代码吗?我注意到您的大多数变量似乎是在提供的代码块之外声明的。如果是这样,你的";Y";被声明为char而不是字符串类型以匹配您的条件类型?

当pWin和cWin返回顶部时,您似乎未能将其设置回零。你可以修复:

restart:    
cWin = 0;
pWin = 0;
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;

cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;
if (cDice1 > pDice1) {
cout << "Computer wins!" << endl << endl;
cWin++;
} if (pDice1 > cDice1) {
cout << "Player wins!" << endl << endl;
pWin++;
} if (pDice1 == cDice1) {
cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
cout << "Player wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}if (cWin > pWin) {
cout << "Computer wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}


}

因为您不会在游戏结束后将pWincWin重置为零。

你应该解决这个问题,但也应该把goto变成另一个while循环,并把while循环的核心变成一个函数。

最新更新