rand [C++ Reference]
Keywords: c,other,rand
Date: 2009-08-06T12:04:29-0700

[[rand]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- fr
- it
- jp
- pl
- ru
- tr

## 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: 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]
        {
           // scale in range [0,1)
           const float scale = rand()/float(RAND_MAX);

           // return range [0,hi]
           return int(scale*hi + 0.5); // implicit cast and truncation in return
        }

Related Topics: srand

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •