1

I'm working on an application. I'm using:

int rand_num = rand() % 100;

To get a random integer between 0 to 99. Now, let's say I got 41, then restarting my application, it's always 41. Same sequence over and over, means it's not really random.

Any solutions?

Ariel Weinberger
  • 2,195
  • 4
  • 23
  • 49

4 Answers4

7

You have to randomize the seed by calling srand(...) (usually with time(0)) whenever you start your application. Note that it is a pseudo-random number generator i.e. the values generated by the rand() function are not uniformly distributed.

JosephH
  • 8,465
  • 4
  • 34
  • 62
  • I don't really understand... Is there a chance to get a snipper, some function like random(min, max);? I'd be greatful! – Ariel Weinberger Feb 13 '13 at 09:17
  • 1
    @Ariel given an interval, you can generate a pseudo-random number by doing `rand() % (max-min)` and incrementing it by `min` – JosephH Feb 13 '13 at 09:19
4

rand generates a pseudo-random number, yes. But you can set the seed.

srand(time(NULL));
int rand_num = rand() % 100;

Set the seed only once.

Or you can use one of the methods from <random>.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
3

Use the following:

#include<time.h>

srand(time(NULL));

It will change the seed of pseudo-random generator.

For more information see this.

Alex
  • 9,891
  • 11
  • 53
  • 87
3

Correct. rand() returns a pseudo-random number. The sequence from a given start is deterministic. You can alter the starting point using srand().

Clyde
  • 7,389
  • 5
  • 31
  • 57