Pergunta

I'm having trouble with this "random number game".
I want the random number to keep it's value only for the inner do while and change when the user decides to try again. I thought adding the srand outside of the loop would change the value every time, but it seems that's not the case.

//Libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;

//Global Constants


//Function Prototypes
int rnd();//random number function

//Execution Begins Here
int main(int argc, char *argv[]){
    //Declare Variables
    unsigned int seed=time(0);
    int n;
    char a;

    //set the random number seed
    srand(seed);
    do{
        do{
           //Prompt user;
           cout<<"*** Random Number Guessing Game *** \n"
               <<"    Guess a number between 1-10,   \n"
               <<"     Enter your number below!     \n";
           cin>>n;
           //process
             if(n<rnd()){
             cout<<" Too low, try again.\n";

             }else if(n>rnd()){
             cout<<" Too high, try again.\n";

             }else if(n==rnd()){
             cout<<rnd()<<" Congradulations you win!.\n";
             }
        }while(n!=rnd());
        cout<<"try again? (y/n)\n";
        cin>>a;
    }while(a=='y' || a=='Y');
    system("PAUSE");
    return EXIT_SUCCESS;
}
int rnd(){
    static int random=rand()%10+1;
    return random;
}
Foi útil?

Solução

Imagine a long line of "pseudo-random" numbers. There's a pointer to some place in the line and calling rnd() prints out the number being pointed to and moves the pointer to the next number. The next call to rnd() does the same thing. Unless two of the same numbers happen to be right next to one another, which can happen but is unlikely, you'll get two different numbers for two different calls to rand. When you call srand you basically set the pointer to a known point on the line so calls to rnd() will return what they did before.

In pictures:

srand(0)
... 1 9 3 4 9 7 ...
  ^  (srand puts the pointer to 9.)
a call to rand returns 9 and updates the pointer:
... 1 9 3 4 9 7 ...
        ^ 
the next call to rnd() will return 3.

If you call srand(0) again it'll be 
... 1 9 3 4 9 7 ...
      ^  
and a call to rnd() will return 9 again.

If you want to keep the same "random" number call rnd once and save the value until you need it again rather than calling rnd each time.

Outras dicas

Use srand(time(NULL)); instead of srand(seed);. Or you can change

unsigned int seed=time(0);  
                       ^ You are seeding same value every time  

to

unsigned int seed=time(NULL);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top