C ++数字猜谜游戏

时间:2018-04-30 08:37:00

标签: c++

我遇到了让这个C ++代码按照我的意愿工作的问题。

它是一个通用数字猜谜游戏,计算机选择用户猜测它的随机数。他们有5次尝试,根据他们的猜测与正确答案的距离,选择了一个输出。

问题是,当猜测大于生成的随机数时。没有输出。如果猜测值低于随机数,则代码可以正常工作。

#include <iostream>
#include <cstdlib> // Used for random num generator
#include <ctime> // Used for the seed

using namespace std;

int main()
{
   srand(static_cast<unsigned int> (time(0)));
   const int MAX_NUMBER = 100;
   int num = (rand() % MAX_NUMBER) + 1;
   int tries = 0;   // Number of times player has guessed
   int guess;       // Player's current guess

   cout << "\tGuess my Number" << endl << endl;
   cout << "Guess my number between 1 and ";
   cout << MAX_NUMBER << "." << endl << endl;

   do
   {
       cout << "Enter a guess; ";
       cin >> guess;
       ++tries;

       int diff = (num - guess);

       if (diff >= 50)  // If guess is off by 50 or more
       {
           if (guess < num)
               cout << "Way to Low!\n";
           else
               cout << "Way to high!" << endl;
       }

       if (diff >= 30 && diff < 50) // If guess is off by 30 to 50
       {
           if (guess < num)
               cout << "That guess was rather low!\n";
           else
               cout << "That guess was rather high!" << endl;
       }

       if (diff >= 15 && diff < 30) // If guess is off by 15 to 30
       {
           if (guess < num)
               cout << "That guess was low!\n";
           else
               cout << "That guess was high!" << endl;
       }

       if (diff > 0 && diff < 15) // If the guess is off under 15
       {
           if (guess < num)
               cout << "That guess was some what low.\n";
           else
               cout << "That guess was some what high." << endl;
       }
   } while ((guess != num) && (tries <= 5));

   if (guess == num)
   {
       cout << endl;
       cout << "You win! You got it in " << tries << " tries!";
       cout << endl;
   }
   else {
       cout << endl;
       cout << "You ran out of guesses!" << endl;
   }

   system("pause"); // Used to hold open the output window.
   return 0;
}

如果有人能指出我正确的方向,我会很感激。

2 个答案:

答案 0 :(得分:7)

问题出在条件是,如果guess大于numdiff将是否定的,但您不会考虑:

if (diff >= 50)

您必须从abs开始(num-guess)才能使其正常运行。

只需更改此行:

int diff = (num - guess);

int diff = abs(num - guess);

答案 1 :(得分:1)

您的diff等于num - guess,这意味着如果guess大于num,您最终会得到负值。但是,您永远不会检查diff是否为负数,因此您永远不会输入您的条件