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 ...

9
  • Have you tried using the random header? Commented Jul 1, 2014 at 13:46
  • 2
    Seed only 1 time in your application. Never ever seed in a loop. Commented Jul 1, 2014 at 13:46
  • 4
    This is silly-mistake #1 related to rand with approx. 1 million questions per week. Only srand once, not every time. Commented Jul 1, 2014 at 13:48
  • 1
    BTW, you may use std::uniform_int_distribution<> in C++11. Commented Jul 1, 2014 at 13:51
  • 1
    I think all the explanations you need can be found here: how to generate different random number in a loop in C++?. It was right of findable from the Related section at the right. Pleas do a bit more research efforts before asking. Commented Jul 1, 2014 at 14:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.