/* This program prints ten random real numbers. The source code explains how to use random numbers in C++. */ #include #include // cstclib defines functions rand() and srand() and the constant RAND_MAX #include // ctime defines the time() function that is used to initialize // the random number generator. int main() { srand(time(0)); // Initialize the random number generator. If this is not done, // then the program will print out exactly the same random // numbers each time it is run. The function time(0) returns // the number of seconds since January 1, 1970 (a so-called // UNIX time stamp). This means that when the program is run // at different times, it will output different numbers. cout << "\nTen random numbers between 0 and 1, inclusive:\n\n"; for (int i = 0; i < 10; i++) { int random_int = rand(); // A random integer between 0 and RAND_MAX, inclusive. double random_real = static_cast(rand()) / RAND_MAX; // A random double between 0 and 1, inclusive. If you // don't want to include 1 in the possible valued, // use: random_real = rand() / (RAND_MAX + 1.0); cout << " " << random_real << endl; } cout << endl; }