gpt4 book ai didi

c++ - 猜谜游戏的问题

转载 作者:行者123 更新时间:2023-11-30 03:43:31 26 4
gpt4 key购买 nike

我需要做一个猜谜游戏,程序会生成一个随机数,用户必须猜测这个数字。如果用户猜中数字少于 10 次,程序会向他们表示祝贺,并让他们知道他们猜不到 10 次。如果他们的猜测超过 10 次,那么它会让他们知道它超过 10 次,等等。

我面临的问题是,例如,如果用户在 3 次尝试中猜到了数字,然后决定用一个全新的其他数字再次玩,这次在 8 次尝试中猜到了,而不是仍然祝贺他们因为它少于 10 次尝试,所以它计算了上一场比赛的 3 次尝试。这导致程序告诉他们他们已经超过 10 次尝试,即使他们没有。我不知道如何解决这个问题。到目前为止我完成的代码如下:

int main()
{
srand(time(0));
int guess;
int number;
char selection = 'y';
int numberOfGuesses=0;

while(selection == 'y' || selection == 'Y')
{
number = rand() % 1000 + 1;

cout << "I have a number between 1 and 1000.\nCan you guess my number?\nPlease type your first guess: ";
cin >>guess;

do
{
if(number > guess)
{
cout << "Too low. Try again: " << endl;
cin >> guess;
numberOfGuesses++;
}
if (number < guess)
{
cout << "Too high. Try again: " << endl;
cin >> guess;
numberOfGuesses++;
}

}

while(number != guess);

if(numberOfGuesses < 9)
{
cout << "You guessed the number in less than 10 guesses!\n Would you like to play again (y or n)?";
cin >> selection;
}
else if(numberOfGuesses > 9)
{
cout << "You guessed the number\n Would you like to play again (y or n)?";
cin >> selection;
}

else if(numberOfGuesses == 9)
{
cout << "You guessed the number.\n Would you like to play again (y or n)?";
cin >> selection;
}

}

return 0;
}

最佳答案

问题是您没有重置计数器。只需将 int numberOfGuesses=0; 放在 while 循环中:

while(selection == 'y' || selection == 'Y')
{
int numberOfGuesses=0;
....
}

关于c++ - 猜谜游戏的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026955/

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