简体   繁体   English

C ++随机数猜测游戏

[英]C++ Random number guessing game

I have to write a program that will run a random guessing game. 我必须编写一个可以运行随机猜谜游戏的程序。 The game is to be numbers from 1-100, the guesser gets 20 tries and at the end is supposed to be asked if they would like to play again. 游戏的数字是1-100,猜测者进行20次尝试,最后应询问他们是否想再次玩。 There also has to be multiple options for print outs if the guesser is to high or low. 如果猜测值太高或太低,打印输出也必须有多个选项。 I have part of my program done I know I still need to add the other options for print outs but right now my issue is that when I try to run what I have it says successful but then there is an error that says that the variable "number" is being used without be initialized. 我已经完成了程序的一部分,我知道我仍然需要为打印输出添加其他选项,但是现在我的问题是,当我尝试运行我说过的内容时,它说成功了,但是出现了一个错误,指出变量“数字”正在使用而未初始化。 I am not sure what to do to get it initialized apparently. 我不确定该如何进行初始化。 (I am new to C++) I have updated my program and am now having a different issue. (我是C ++的新手) 我已经更新了程序,现在遇到了另一个问题。 My program runs but if the guess is lower than the number it prints Too high try again and Too lower try again but when the number is too high it just prints Too high try again. 我的程序运行,但是如果猜测值低于它打印的数字太高,请重试,而太低的颜色再尝试,但当数字太大时,它只会打印过高。 I also noticed that when the user chooses to play again the tries counter is not resetting with the game. 我还注意到,当用户选择再次玩游戏时,尝试计数器不会随着游戏重置。 One last thing I have to add more messages for when they win, lose and are asked to play another game and I have to use random number to choose among them. 最后一件事,当他们获胜,失败并被要求玩另一局游戏时,我必须添加更多消息,而我必须使用随机数在其中选择。 SO any advice on the best route to do that would be great 因此,关于最佳路线的任何建议都将是很棒的

#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;

}

[EDIT: Added cast to get rid of compiler warning.] [编辑:添加了强制转换以摆脱编译器警告。]

As Jim Rhodes said in a comment, the problem is with the line 正如Jim Rhodes在评论中所说,问题出在生产线

srand(number>0);

srand() is used for initialising the random number generator, so it doesn't make sense to call it with number>0 , or even with number at all. srand()用于初始化随机数生成器,所以它没有任何意义与叫它number>0 ,或甚至number在所有。 It wants a "seed" value, that should be different every time you run the program. 它需要一个“种子”值,每次运行该程序时该值都应该不同。 A common way to get such a seed is by using the system time: 获取此类种子的一种常见方法是使用系统时间:

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

You might need to #include another header to get access to time() . 您可能需要#include另一个标头才能访问time()

The problem the compiler is warning you about is with these two lines: 这两行是编译器警告您的问题:

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

Here, you haven't given the variable number an initial value, so it's uninitialised -- you have absolutely no way of knowing what the value might be at this point. 在这里,您没有给变量number一个初始值,所以它没有被初始化 -您绝对无法知道此时的值。 In fact, it's likely to change every time you run your programme. 实际上,每次您运行程序时,它都有可能改变。 Next you're asking whether the mystery value is greater than zero -- it might be, it might not, but you just don't know. 接下来,您要询问神秘值是否大于零-可能是,也可能不是,但您只是不知道。 It's mystery behaviour, which is what the compiler is warning you about. 这是一个神秘的行为,这是编译器警告您的。

Now of course, you're trying to initialise the random seed, so having this mystery behaviour might be what you're after! 当然,现在,您正在尝试初始化随机种子,因此您可能会追求这种神秘行为! But unfortunately even that isn't going to work as it stands. 但是不幸的是,即使那样,它也无法正常工作。

In C++, the expression number>0 is boolean, that is, the result of the expression is either true or false . 在C ++中,表达式number>0为布尔值,即表达式的结果为truefalse But the srand() function takes an unsigned int as it's argument, so the compiler has to convert the bool to an unsigned , and it does so by changing false to 0 , and true to 1 (probably: I believe it's technically up to the implementation). 但是srand()函数将unsigned int作为其参数,因此编译器必须将bool转换为unsigned ,并且可以通过将false更改为0 ,将true更改为1 (可能是:我认为这在技术上取决于实施)。 So no matter what the initial value of number , your random seed is only going to have one of two possible values -- not very random at all! 因此,无论number的初始值是number ,您的随机种子都只会具有两个可能的值之一-根本不是非常随机!

Better would be to use a random seed based on something (relatively) unpredictable. 最好是使用(相对)不可预测的随机种子。 It's common for non-cryptographic needs to initialise a seed based on the current time. 非加密需求通常会基于当前时间初始化种子。 Something like: 就像是:

#include <ctime>

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

would be fine. 会没事的。

One problem that I see is that you are picking a new random number for each user guess. 我看到的一个问题是,您为每个用户猜测都选择了一个新的随机数。 This is wrong. 错了

To fix this you should put the 要解决此问题,您应该将

number=rand()%100+1;

line before the do while loop that loops asking for guesses. 在do while循环之前的一行,循环进行猜测。

A second problem is the condition on that loop is not correct. 第二个问题是该循环的条件不正确。 You should loop until number == guess not number > guess and put the both couts that tell the user if the guess is high or low inside the loop and increment your tries inside the loop as well. 您应该循环直到数字==猜测而不是数字>猜测,然后将两个告诉用户猜测值是在循环内是高还是低的提示同时在循环内增加尝试次数。

Also you probably want to have an outer do while() loop for the question that asks you to play again instead of this loop being after the loop that waits till the user gets the right number. 另外,您可能希望有一个外部do while()循环来处理要求您再次播放的问题,而不是在等待用户获得正确编号的循环之后执行此循环。

Initialize your variables (always!!) before using them, otherwise you're calling for undefined behavior (or even coppiler errors) within any operations with these! 在使用它们之前初始化变量(总是!),否则您将在使用这些变量的任何操作中调用未定义的行为(甚至是coppiler错误)!

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

NOTE (for downvoters, doubting commenters): 注意 (对于拒绝投票者,怀疑评论者):
Of course this answer doesn't tell, how to get the srand(number>0); 当然,这个答案并不能说明如何获得srand(number>0); statement right for the desired result (ie initializing number with a more appropriate value than 0 ), but it solves the compile time error asked for in first place, and is good advice for any other scenario, resulting in a similar compiler error (warning). 该语句适合于所需的结果(即,使用比0更合适的值初始化number ),但是它可以解决首先要求的编译时错误,并且对于任何其他情况都是一个很好的建议,从而导致类似的编译器错误(警告) 。 Getting number initialized with an appropriate value to pass to srand() seed method to get the right results expected at runtime, is a completely different question and should be asked as such. 获取具有适当值的number初始化以传递给srand()种子方法,以在运行时获得正确的结果,这是一个完全不同的问题,应这样问。

May I suggest using the gettimeofday function, as a way to provide a seed to your random function? 我可以建议使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM