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

问题描述 投票:0回答:4

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

然而,当我运行该程序时,它只是打印:“让我们玩游戏。我会想到一个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;





    }



}

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

c++ loops random
4个回答
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);

1
投票

在“让我们玩游戏之后你的程序没有打印任何东西的原因。我会想到一个1-100的数字。试着猜测它。”是你编写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
投票

您可以定义一些变量,使您的代码更容易理解,如下所示:

#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之类的数字。然后,你可以添加1;这将只生成正整数。


0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.