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:
// note the float literals are important, otherwise the integers could // overflow when 1 is added. int randomNumber(int hi) //the correct random number generator for [0,hi-1] { // scale in range [0,1) const float scale = rand()/(float)RAND_MAX; // return range [0..hi-1] return (int)(scale*hi); // implicit cast and truncation in return }
Another, naïve manner to clamp the random to a range [X,Y] is to use the following: k=rand()%(Y-X+1)+X; , but take into consideration the note above.
Related Topics: srand