Namespaces
Variants
Views
Actions

std::rand

From cppreference.com
< cpp‎ | numeric‎ | random
Revision as of 11:07, 15 June 2012 by P12 (Talk | contribs)

Template:cpp/numeric/random/sidebar

Defined in header <cstdlib>
int rand();

Returns a uniformly distributed pseudo-random integral value between 0 and RAND_MAX (0 and RAND_MAX included).

srand() should be called before any calls to rand() to initialize the random number generator.

Contents

Parameters

(none)

Return value

Pseudo-random integral value between 0 and RAND_MAX.

Example

#include <cstdlib>
#include <iostream>
#include <ctime>
 
int main() 
{
    std::srand(time(0)); //use current time as seed for random generator
    int uniform_random_variable = std::rand();
    std::cout << "Uniform random value on [0 " << RAND_MAX << "]: " 
              << uniform_random_variable << '\n';
}

Possible output:

Uniform random value on [0 2147483647]: 1373858591

See also

Template:cpp/numeric/random/dcl list srand