我正在创建一个只是Shell游戏的C ++程序。我有一个问题,如果用户的猜测是不正确的,他们再次猜测,它不再检查猜测。相反,它只是返回主菜单。我猜这一定是范围问题,但我不太确定。任何帮助将不胜感激。
#include <iostream>
#include <array>
using namespace std;
void displayMenu();
void displayGameMenu ();
int main() {
int userChoice;
int n;
do {
int incorrectGuess;
displayMenu();
cin >> userChoice;
if (userChoice == 1) {
displayGameMenu();
cin >> n;
if (n < 3) {
cout << "The minimum number of cups is 3. Please enter the amount of cups you'd like to play with: " << endl;
cin >> n;
}
else {
bool cups[n];
cout << "The game is ready, and the ball is under one of the " << n << " cups. Guess which cup the ball is in: \n";
for (int i = 0; i < n; i++) {
cout << "Cup " << i + 1 << "\n";
}
cout << "Enter -1 to leave the game. ";
int ballLocation = rand()%(n-3) + 3;
cups[ballLocation] = true;
int userGuess;
cin >> userGuess;
if (userGuess == ballLocation) {
cout << "Congrats! You win! What would you like to do now?\n";
return 0;
}
else if (userGuess != ballLocation) {
cout << "Nope! Not it! Try again: \n";
for (int i = 0; i < n; i++) {
cout << "Cup " << i + 1 << "\n";
}
cout << "Enter -1 to leave the game. ";
cin >> userGuess;
ballLocation = rand()%(n-3) + 3;
incorrectGuess++;
}
else if (userGuess > n) {
cout << "Invalid guess! Try again: ";
for (int i = 0; i < n; i++) {
cout << "Cup " << i + 1 << "\n";
}
cout << "Enter -1 to leave the game. ";
cin >> userGuess;
}
else if (incorrectGuess == 4) {
cout << "You're out of guesses! Nice try! \n";
return 0;
}
else if ( userGuess == -1) {
return 0;
}
}
}
}
while (userChoice != 2);
}
void displayMenu() {
cout << "Welcome to the Shell Game! Please choose one of the menu options below.\n";
cout << "1. Play the Game!\n";
cout << "2. Quit.\n";
cout << "Enter choice here: " << endl;
}
void displayGameMenu() {
cout << "Thank you for deciding to play the Shell Game. How many cups (3 is the minimum) would you like to play with? " << endl;
}
答案 0 :(得分:1)
您的while
循环将执行范围括号中的所有内容:
do
{
// EVERYthing in here is performed within the while loop
} while ();
现在看看你的范围:
do
{
...
displayMenu();
...
} while (userChoice != 2);
你看到了问题吗?您告诉您的while
循环在循环的每次迭代中显示菜单!您可能希望将displayMenu()
放在do while