【问题标题】:C++ Number guessing gameC++ 猜数字游戏
【发布时间】:2018-04-30 08:36:59
【问题描述】:

我无法让这个 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;
}

如果有人能指出我正确的方向,我将不胜感激。

【问题讨论】:

  • 如果您的guess 大于您的num,您的diff 将为负数,您在任何地方都无法处理。
  • abs() 给出了绝对值,所以int diff = abs(num-guess); 将解决这个问题。 cplusplus.com/reference/cstdlib/abs
  • 谢谢,abs 做到了。

标签: c++


【解决方案1】:

问题在于 if 条件,如果 guess 大于 numdiff 将是负数,但您没有考虑到这一点:

if (diff >= 50)

您必须从(num-guess) 获取abs 才能使其工作。

只需更改此行:

int diff = (num - guess);

int diff = abs(num - guess);

【讨论】:

  • 谢谢,就是这样。那三个小字母让我退缩了:P
【解决方案2】:

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

【讨论】:

  • 谢谢,有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 2014-11-25
  • 2016-06-21
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多