0

I write a function to generate random number, I call this function every 10 mS.

What I get is surprising, my number generate are a sequence of 3 ( 0,3,6,9,12,...)

Here's my function :

int utilitaireUDP::genereNombreAleatoire(int a, int b){
    int nombre_aleatoire = 0; //Sert a remplir la structure
    srand(time(NULL)); // initialisation de rand
    nombre_aleatoire = rand()%(b-a) +a;;
    return nombre_aleatoire;
}

Do I forget something ? Is the problem linked to my CPU ( because random number are generate from my internal clock ) ?

EDIT : Thanks everyone !

I use this post to add something, I've got this function :

bool utilitaireUDP::genererBooleen(){
    if (genereNombreAleatoire(0,1) == 0){
        return true;
    }
    else {
        return false;
    }
}

And this generate me only true, but I put the srand in my main now ... And it works perfectly for int ...

Evans Belloeil
  • 2,413
  • 7
  • 43
  • 76

1 Answers1

6

It's rarely useful to call srand more than once during a run of a program; in particular, don't try calling srand before each call to rand, in an attempt to get "really random" numbers.

Remove srand(time(NULL)); from your function and place it at program start up so that it called only once.

haccks
  • 104,019
  • 25
  • 176
  • 264