rand() isn't random at all - it's just a mathematical function which produces a sequence of numbers which are superficially random. If you know the algorithm, they're not random at all.
Call rand() often enough, you will start repeating the same sequence over again. This is known as the period of the random number generator. Really good algorithms like the Mersenne Twister have huge periods.
The only thing you can change is the seed, which changes your start position in the sequence.
Example
A really simple rand() has a period of 10, and generates
[tt]0 2 5 3 9 7 6 1 8 4[/tt]
If the seed is 1 say, then it will always start by giving you the answer 0, followed by 2 then 5 etc
If you change the seed to 4 say, then you'll get 3, 9, 7 etc
In your C code, you typically start your program with
Code:
#include <stdlib.h>
#include <time.h>
int main ( ) {
srand( (unsigned)time(NULL) );
}
So long as you don't run your program twice in the same second, you'll get different answers from rand(), because you'll keep changing the start position (seed value)
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.