我需要做一个Guessing游戏,程序生成一个随机数,用户必须猜测数字。如果用户在少于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;
}
答案 0 :(得分:2)
问题是您没有重置计数器。
只需将int numberOfGuesses=0;
放在while
循环中:
while(selection == 'y' || selection == 'Y')
{
int numberOfGuesses=0;
....
}
答案 1 :(得分:0)
您需要在每场比赛前将numberOfGuesses
设置为0。程序首次启动时,您的程序只会设置一次。
答案 2 :(得分:0)
每轮结束后,您没有将numberOfGuesses
重置为零。您可以使用以下几种方法之一解决问题。
在第一个numberOfGuesses
循环结束时将while
的值重置为零。
while(selection == 'y' || selection == 'Y')
{
...
numberOfGuesses = 0;
}
在while
循环开始之前,不要定义变量。将其定义为第一个语句并将其初始化为零。
while(selection == 'y' || selection == 'Y')
{
int numberOfGuesses = 0;
...
}