简单的数字猜游戏.c++

Simple Number Guessing Game. C++

本文关键字:c++ 猜游戏 数字 简单      更新时间:2023-10-16

我一直在尝试制作一个简单的游戏,其中计算机生成一个随机数,您尝试猜测它。它还会存储你"尝试"猜测的次数。

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


    }

}

我不明白为什么这不起作用,有人能解释一下吗?

程序在"Let's play a game "之后不打印任何内容的原因。我想一个数字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;
      }
   }

您可以定义一些变量,使您的代码更容易理解,像这样:

#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;这将只生成正整数。

这里应该使用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);

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

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

你也循环猜测部分,但你忘了问用户一个新的数字。我建议将cin << guess移到for循环中。