Why do I get the same result with rand() every time I compile and run? [duplicate]

You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()

For example

srand(time(NULL));
rand();//now returns a random number

The reason is that the random numbers provided by rand() (or any other algorithm based function) aren’t random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.

So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.

Leave a Comment