rand

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: Many naive methods of clamping the produced random number to a range will not in general produce a uniform distribution. Examples include simple use of % (modulus) and scaling with integer or floating point division. Instead use this algorithm to generate a proper uniform distribution of random numbers >= 0 and < limit:

    // Assumes limit <= RAND_MAX
    int randomNumber(int limit)
    {
        unsigned int n;
        unsigned int mask = 0xFFFFFFFF;
 
        while(mask > limit * 2) mask >>= 1;
 
        do {
            n = rand();
            n &= mask;
        } while (n >= limit);
 
        return n;
    }

Related Topics: srand