c++ - 简单的数字猜谜游戏。 C++

标签 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;





    }



}

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

最佳答案

您的程序在“让我们玩一个游戏吧。我会想出一个数字 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;
      }
   }

关于c++ - 简单的数字猜谜游戏。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837559/

相关文章:

c++ 读取 flash AIR NativeAplication 参数

java - ArrayIndexOutOfBounds 应在边界内的对象上

r - 循环遍历数据框中的列并根据 R 中的特定条件连接字符串

c++ - 在 C++ 中创建随机无向图

javascript - CasperJS/PhantomJS,一些测试随机失败

c++ - 查找正在运行的 valgrind 版本

c++ - 具有自定义散列/相等函数的 unordered_map - 函数不会被调用

c++ - 重温 C++ 指针和函数

c++ - 在 FOR 循环中声明变量

javascript - Javascript 中 float 与整数的比较