Defined in header <stdlib.h> | ||
int rand(); | ||
Returns a pseudo-random integer value between0 andRAND_MAX (0 andRAND_MAX included).
srand() seeds the pseudo-random number generator used byrand().Ifrand() is used before any calls tosrand(),rand() behaves as if it was seeded withsrand(1).Each timerand() is seeded withsrand(), it must produce the same sequence of values.
rand() is not guaranteed to be thread-safe.
Contents |
(none)
Pseudo-random integer value between0 andRAND_MAX, inclusive.
There are no guarantees as to the quality of the random sequence produced.In the past, some implementations ofrand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between1 and0 between calls).rand() is not recommended for serious random-number generation needs, like cryptography.
POSIX requires that the period of the pseudo-random number generator used byrand be at least232
.
POSIX offered a thread-safe version of rand calledrand_r, which is obsolete in favor of thedrand48 family of functions.
#include <stdio.h>#include <stdlib.h>#include <time.h> int main(void){srand(time(NULL));// use current time as seed for random generatorint random_variable= rand();printf("Random value on [0,%d]: %d\n",RAND_MAX, random_variable); // roll a 6-sided die 20 timesfor(int n=0; n!=20;++n){int x=7;while(x>6) x=1+ rand()/((RAND_MAX+ 1u)/6);// Note: 1+rand()%6 is biasedprintf("%d ", x);}}
Possible output:
Random value on [0,2147483647]: 4487495743 1 3 1 4 2 2 1 3 6 4 4 3 1 6 2 3 2 6 1
| seeds pseudo-random number generator (function)[edit] | |
| maximum possible value generated byrand() (macro constant)[edit] | |
C++ documentation forrand | |