Syntax:
#include <cstdlib> int rand( void );
The function rand() returns a pseudorandom integer between zero and RAND_MAX. An example:
srand( time(NULL) ); for( i = 0; i < 10; i++ ) printf( "Random number #%d: %d\n", i, rand() );
Note: Do not use % (modulus) to limit the random numbers generated. The randomness is heavily reduced. Instead use this algorithm to generate a proper distribution of random numbers between 0 and another number:
int randomNumber(int hi) //the correct random number generator for 0-hi { int value=((float)rand()/RAND_MAX)*(hi+1); if(value>hi) { value = 0; } return value; }
Related Topics: srand