简单数字猜测游戏。 C ++

时间:2014-07-19 06:44:04

标签: c++ loops random

我一直试图制作一个简单的游戏,计算机生成一个随机数,你试着猜它。它还会存储您所做的猜测量和尝试次数。

然而,当我运行该程序时,它只是打印:"让我们玩游戏。我会想到一个1-100的数字。试着猜测它。"

这是我的代码:

    #include <iostream>

    int main()

    {
        using namespace std;

        int the_number;
        int guess;
        int tries;

        the_number = rand() % 101 + 1;

        cout << "Let's play a game!";
        cout << "I will think of a number 1-100. Try to guess it.";
        cout << endl;
        cin >> guess;

        for (tries = 0; tries++;)
        {
            if (guess == the_number)
            {
                cout << "You guessed it!";
                cout << "And it only took you: " << tries;
            }
            else if (guess < the_number)
            {
                cout << "Higher";
                tries++;
            }


            else if (guess > the_number)
            {
                cout << "Lower";
                tries++;
            }

            else
                cout << "That's not even in range!";
            return 0;





    }



}

我不明白为什么这不起作用,有人可以解释为什么不行吗?

4 个答案:

答案 0 :(得分:1)

你的节目在&#34之后没有打印任何内容的原因;让我们玩游戏。我会想到一个1-100的数字。试着猜测它。&#34;是你编写for循环的方式。

for ( tries = 0; tries++; )

在没有做任何事情的情况下突破循环,因为tries++评估为0

此外,为了使您的程序正常工作,您需要添加更多代码来读取猜测。像下面的代码一样,应该可以工作。

   for (tries = 0; ; tries++)
   {
      if (guess == the_number)
      {
         cout << "You guessed it!";
         cout << "And it only took you " << tries << " tries.\n";
         break;
      }
      else if (guess < the_number)
      {
         cout << "Higher";
         cin >> guess;
      }

      else if (guess > the_number)
      {
         cout << "Lower";
         cin >> guess;
      }
   }

答案 1 :(得分:1)

您可以定义几个变量,以使您的代码更易于理解,例如:

#include <iostream>
using namespace std;

int main()
{char EndGame = 'N';
    int MyNumber = 150 , playerguess;
    cout << "I have a number between 1 and 100.\nCan you guess my number ??\nPlease type your first guess.\n?" << endl;

    do{
        cin >> playerguess;
    if (playerguess > MyNumber) {
        cout << " Too High. Try again." << endl;

    }

    else if (playerguess == MyNumber) {
        cout << "Excellent ! You Got It ! \n If you want to exit press Y" << endl;
        cin >> EndGame;
        break;

    }
    else {
        cout << " Too Low. Try again." << endl;
    }
    } while (1);
return 0;
}

这将使数字等于 150 。每次用户输入一个值时,控制台都会确定该值是较高,较低还是等于该数字。

如果您想每次都使其成为一个随机数,则可以简单地使用<random>库,并使用带有100或101之类的数字的模块运算符。这只会产生正整数。

答案 2 :(得分:0)

你的for循环是错误的(它需要3件事:初始化,检查条件和每个循环后的todo步骤。 例如:

for (tries = 0; tries < 5; tries++) 

您也可以循环猜测部分,但是忘记向用户询问新号码。我建议将cin << guess移到for循环中。

答案 3 :(得分:0)

您应该在此处使用while循环,而不是for

while (the_number != guess)
{
    //
    //
}

尝试使用新的<random>标头代替rand()功能:

#include <random>

std::random_device rd;

std::default_random_engine engine(rd());
std::uniform_int_distribution<int> uniform_dist(1, 100);

the_number = uniform_dist(engine);