我正在用 C 制作一個骰子游戲。我想知道為什么它不重新啟動回圈。游戲是最好的 3。只要玩家想繼續玩,它就應該重新開始回圈。然而,它只重新啟動一次回圈。我第二次按“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);
}
}
}
uj5u.com熱心網友回復:
首先,這是你的全部代碼嗎?我注意到您的大部分變數似乎是在提供的代碼塊之外宣告的。如果是這樣,您的“Y”是否被宣告為字符而不是字串型別以匹配您的條件型別?
看起來您在回傳頂部時未能將 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);
}
}
}
uj5u.com熱心網友回復:
因為你不會在比賽結束后重置pWin 并cWin歸零。
你應該解決這個問題,但也可以把它goto變成另一個 while 回圈,并把那個 while 回圈的內容變成一個函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360353.html
