Minoru
Minoru

Reputation: 1730

c++ - rand() always outputs the same numbers on every run

I'm using C++ on Visual Studio 2010. The problem is that I try to generate an array of random numbers, but the results are always the same on every run. For example:

Run 1:
[0 20103 43281 37162 101 299]
Stop
Run 2:
[0 20103 43281 37162 101 299]
Stop
...

So, my code is generating random values for the array, but they are always the same values everytime I run the code (even if I clean the build). I really need to generate random values for every run.

Here's some sample code, the complete code is full of simple operations:

...
srand(time(NULL));
for (int i = 0; i < 31; i++){
    x[i] = x[i] + rand();
}

Any ideas?

Please, note the presence of the srand(time(NULL)); line. It's already on the code, still the output is not fine.

Upvotes: 0

Views: 2081

Answers (2)

user3502455
user3502455

Reputation:

Try randomizing like this:

int a;
a=rand()%*whatever range you want it to be*;

You can also change the srand(time(NULL));, because NULL means 0.

srand(time(1000));

It's unit is milliseconds, so 1000 is one second.

Hope it helps!

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

Please, note the presence of the srand(time(NULL)); line. It's already on the code, still the output is not fine.

Seeding prepares a new pseudo-random sequence; rand calls advance you along that sequence. Every time you call seed with the same argument, you start that same sequence again.

Since your seed argument changes only once per second, if you run your program more than once per second, you will see the same pseudo-random sequence.

I would recommend seeding with a little more entropy, though how to do this is largely platform-dependent. On Linux I like to write srand(time(NULL) ^ getpid()).

Also remember to seed only once in your program (and it appears that you're getting this right).

Upvotes: 1

Related Questions