【问题标题】:C++ Random number guessing gameC++ 随机数猜谜游戏
【发布时间】:2013-10-29 02:14:27
【问题描述】:

我必须编写一个运行随机猜谜游戏的程序。游戏是从 1 到 100 的数字,猜者有 20 次尝试,最后应该被问到是否想再玩一次。如果猜测器是高或低,还必须有多个打印输出选项。我已经完成了我的程序的一部分我知道我仍然需要为打印输出添加其他选项但是现在我的问题是当我尝试运行我所拥有的内容时它说成功但是然后有一个错误说变量“ number" 正在使用而没有被初始化。我不知道该怎么做才能让它初始化。 (我是 C++ 新手) 我已经更新了我的程序,但现在遇到了不同的问题。我的程序运行,但如果猜测低于它打印的数字太高再试一次,太低再试一次,但是当数字太高时,它只会打印太高再试一次。我还注意到,当用户选择再次玩游戏时,尝试次数计数器不会随着游戏重置。最后一件事我必须添加更多消息,说明他们何时赢、输并被要求玩另一场比赛,我必须使用随机数在其中进行选择。所以任何关于最佳路线的建议都会很棒

#include <iostream>
#include <iomanip> 
#include <ctime>
using namespace std;
char chr;

int main()
{
srand(time(NULL));                                           //the function that generates random numbers
int number=rand()%100+1;                                     //the range of the random numbers
int guess;                                                   //The guess is stored here
int tries=0;                                                 //The number of tries stored here
   char answer;                                                 //The answer to the question is stored here
answer='y';                  

while(answer=='y'||answer=='Y') 
{
    while (tries<=20 && answer=='y'|| answer=='Y')
    {
    cout<<"Enter a number between 1 and 100 "<<endl;          //The user is asked for a guess
    cin>>guess;                                               //The guess is stored here
    tries++;                                                 //Adding a number for every try
    if(guess==0||guess>100)                                  //If statement that produces an error message if user enters a number out of the peramiters
    {
     cout<<"This is not an option try again"<<endl;          //Error message
    }

    if(tries<20)                                            
    cout<<"Tries left: "<<(20-tries)<<endl;                   //Output to let the user know how many guess they have left

    if(number<guess);                                         //if the guess is to high
    cout<<"Too high try again"<<endl;                         //This message prints if guess it to high

    if(number>guess)                                          //if the guess is to low
    cout<<"Too low try again"<<endl;                          //This message prints if the guess is to low

    if(number==guess)                                          //If the user guesses the number
    {
     cout<<"Congratualtions!! "<<endl;                          //Message printed out if the user guesses correctly
     cout<<"You got the right number in "<<tries<<" tries"<<endl;  //Lets the user know how many guess they used
     answer = 'n';
    }
    if(tries >= 20)                                               //If the user uses all their guesses
    {
    cout << "You've run out of tries!"<<endl;                      //The message that prints when a user is out of guesses
    answer='n';
    }
    if(answer=='n')
    {
     cout<<"Would you like to play again?  Enter Y/N"<<endl;       //asking if play would like to play again
     cin>>answer;                                                  //Store users answer
     if (answer=='N'|| answer=='n')                                //if the user says no
     cout<<"Thanks for playing!"<<endl;                            //This message prints out if they choose not to play again

    else
        number=rand()%100+1;                                        //This starts the game over if they choose to play again
    }

    }
    }

cin>>chr;
    return 0;

}

【问题讨论】:

  • 您在以下行中使用numbersrand(number&gt;0);,但尚未为number 赋值。这真的是你的本意吗?
  • 请忽略@g-makulik的评论,这就像通过关闭火警来“处理”火灾。
  • 您真的想在每次猜测之前更改数字吗?而且您要求再次播放的 do 循环肯定不会执行预期的操作。
  • 最后,while(number>guess) 和 do { 之间的代码有什么意义?这也不会按预期工作。
  • @drescherjm:好点子,如果你把它们写在答案中,我会 +1。

标签: c++


【解决方案1】:

[编辑:添加演员表以消除编译器警告。]

正如 Jim Rhodes 在评论中所说,问题出在这条线

srand(number>0);

srand() 用于初始化随机数生成器,因此用number&gt;0 调用它甚至用number 调用它都没有意义。它需要一个“种子”值,每次运行程序时都应该不同。获取此类种子的常用方法是使用系统时间:

srand(static_cast<unsigned int>(time(NULL)));

您可能需要#include 另一个标头才能访问time()

【讨论】:

  • 我将 srand() 更改为 srand(time(0));并添加了#include,这是我得到'argument'的错误:从'time_t'转换为'unsigned int',可能丢失数据我不确定现在的问题是什么
  • @StacyDoyle:这应该只是一个警告,而不是一个错误。 time() 返回的以秒为单位保存当前时间的整数类型(通常)比 srand() 预期的种子大,但这是我们不介意丢失一些位的少数情况之一,因为我们真正关心的是低位位——每秒都在变化的位。
  • @StacyDoyle:我已经更新了我的答案以包含一个强制转换(转换),告诉编译器我们知道时间值的高位可能丢失并且我们不介意:)
  • 您是否在我的代码中看到另一个错误,该错误会阻止它运行,因为它仍然显示失败。
  • @StacyDoyle:要找到这个错误,假设您输入的猜测值太低。找出将要发生的步骤。特别是,while(number&gt;guess); 行会发生什么?
【解决方案2】:

编译器警告您的问题在于这两行:

int number;
//...
srand(number>0);

这里,你没有给变量number 一个初始值,所以它是未初始化的——你完全无法知道此时的值可能是什么。事实上,每次运行程序时它都可能发生变化。接下来你要问神秘值是否大于零——可能是,也可能不是,但你只是不知道。这是一种神秘的行为,这是编译器警告你的。

当然,现在您正在尝试初始化随机种子,因此您可能会追求这种神秘的行为!但不幸的是,即使这样也行不通。

在 C++ 中,表达式number&gt;0 是布尔值,即表达式的结果是truefalse。但是srand() 函数将unsigned int 作为它的参数,因此编译器必须将bool 转换为unsigned,它通过将false 更改为0true 来实现1(可能:我相信这在技术上取决于实现)。所以无论number 的初始值是多少,你的随机种子只会有两个可能的值之一——根本不是很随机!

最好使用基于(相对)不可预测的随机种子。非加密需要根据当前时间初始化种子是很常见的。比如:

#include <ctime>

std::time_t now = std::time(0);
srand(static_cast<unsigned>(now));

会好的。

【讨论】:

    【解决方案3】:

    我看到的一个问题是,您要为每个用户猜测选择一个新的随机数。这是错误的。

    要解决这个问题,你应该把

    number=rand()%100+1;
    

    在循环询问猜测的 do while 循环之前的行。

    第二个问题是该循环的条件不正确。您应该循环直到 number == guess not number > guess 并将两个 cout 告诉用户猜测是高还是低在循环内,并在循环内增加您的尝试。

    此外,您可能希望为要求您再次播放的问题设置一个外部 do while() 循环,而不是在等待用户获得正确数字的循环之后。

    【讨论】:

      【解决方案4】:

      在使用它们之前初始化你的变量(总是!!),否则你会在使用这些的任何操作中调用未定义的行为(甚至是编译器错误)!

      int number = 0;
      int guess = 0;
      int tries = 0;
      char answer = '\0';
      

      注意(针对反对者、质疑者):
      当然这个答案并没有说明,如何让 srand(number&gt;0); 语句正确获得所需的结果(即使用比 0 更合适的值初始化 number),但它解决了首先要求的编译时错误位置,对于 任何 其他情况是很好的建议,导致类似的编译器错误(警告)。使用适当的值初始化 number 以传递给 srand() 种子方法以在运行时获得预期的正确结果,这是一个完全不同的问题,应该这样问。

      【讨论】:

      • -1。这并不能解决问题,您只是关闭了告诉您有问题的警报!
      • 它解决了编译器错误问题,从来没有被要求做更多的事情!
      • 通过编写错误代码解决编译器错误对 OP 没有帮助。
      • @nhgrif:你喜欢这样回答自己的问题吗?那种没有真正解决根本问题的那种?
      • @g-makulik 我很抱歉我没有恰当地表达我的问题让我再试一次我想让我的程序工作如果有错误让我知道它们是什么和可能的如何修复它们。我希望这可以消除任何困惑。
      【解决方案5】:

      我可以建议使用 gettimeofday 函数来为您的随机函数提供种子吗?

      #include <stdio.h>
      #include <stdlib.h>
      #include <sys/time.h>
      //clock_t times(struct tms *buffer);
      int
      main(int argc, char **argv)
      {
          int a;
          struct timeval _wall;
          gettimeofday( &_wall, NULL ); //(_wall.tv_sec,_wall.tv_usec);
          srand(_wall.tv_usec);
          a = rand() % 100 + 1;
          printf("%d\n",a);
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-29
        • 2019-06-02
        • 1970-01-01
        • 1970-01-01
        • 2021-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多