猜谜游戏,电脑产生随机数

Guessing game where computer generates random number

本文关键字:随机数 电脑 游戏      更新时间:2023-10-16

我正在实现一个猜谜游戏,其中计算机生成随机数与以下代码:

int main()
{
    srand(time(NULL));
    while (true){
        int num = rand() % 10, guess, tries = 0;        
        while (true){
            cout << "Enter number 1 to 10:";
            cin >> guess;
            if (tries > 2)
            {
                break;
            }
            if (guess > num)
            {
                cout << "Too High ! Try again"<<endl;
            }
            if (guess > 10)
            {
                cout << "Error ReEnter 1 to 10n";
            }
            else if (guess < num)
            {
                cout << "Too Low! Try again"<<endl;
            }
            else
            {
                break;
            }
            tries++;            
        }
        if (tries > 2)          
        {
            cout <<"nYou ran out of tries!n";
            cout << "nThe answer is:" << num << endl;
        }
        else
        {
            cout << "nCONGRATZ!! You guess correctly!n";
        }       
        return 0;
    }
}

其中一个问题是:当用户尝试3次时,即使用户在第三次尝试时输入正确,程序仍显示"run out of tries"。

问题:

1。我如何通知用户他们的输入超过了10,并显示一条错误消息,让用户输入从1到10的值?

2。如何纠正上述问题?

这里是一些伪代码,而不是为您编写程序。

get a random number rand()%10+1  1..10 call it R
loop
  get user input N
  if N == R then show OK and break loop
  if N < R show too low 
  else show too high
  increment tries
  if tries == 3 then break loop
end loop

你有太多的if else条件,使你的代码不必要地复杂,回答你的第二个问题,特别是不需要的行为是由:

  if (tries > 2)
  {
      break;
  }

退出循环,而不考虑猜测,因为它只依赖于尝试的次数。关于你的第一个问题,我决定为你提供一个更简单的实现,包括它的答案。

您可以将while循环替换为do-while循环,当猜出随机数时终止,即:

int main(){
    // initialize random seed
    srand (time(NULL));
    // generate a random number within [1,10]
    int secretRandom = rand() % 10 + 1;
    // initialize 
    int yourGuess = 11;
    // input loop
    string promptMessage = "Type a a number from 1 to 10."
    do{
        cout << promptMessage << 'n';
        // read input
        cin >> yourGuess >> endl;
        // guessed number relatively to the randomly generated  
        if (secretRandom < yourGuess) cout << "The secret number is lowern";
        else if (secretRandom > yourGuess)  cout << "The secret number is highern";
    }while(yourGuess != secretRandom) 
    // if you guess the random number exit the loop and display success message
    cout << "You guessed right!n";
return 0;
}

为了减少对特定数字的猜测量,您可以将do-while循环和成功消息包含在for循环中,例如:

int numberOfGuesses = 3;
for (int i = 0; i <= numberOfGuesses; ++i){
    //...
} 

如果你想强制用户输入1到10之间的数字,你可以这样做:

int yourGuess = 11;
int lowerBound = 0;
int upperBound = 10;
do{
    cin >> yourGuess;
    // not type safe
}while(yourGuess < lowerBound || yourGuess > upperBound);