gpt4 book ai didi

C++ 程序未正确执行,可能是范围问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:14:32 26 4
gpt4 key购买 nike

我正在努力创建一个简单的 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;
}

最佳答案

您的 while 循环将执行它之前范围括号中的所有内容:

do
{
// EVERYthing in here is performed within the while loop
} while ();

现在看看你的范围:

do
{
...
displayMenu();
...
} while (userChoice != 2);

你看到问题了吗?您正在告诉您的 while 循环在循环的每次迭代中显示菜单!您可能希望将 displayMenu() 放在 do while

之前

关于C++ 程序未正确执行,可能是范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35590402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com