Example which displays 20 random integers
#include <iostream>
#include <cstdlib> // srand and rand functions
#include <ctime> // time function
using namespace std;
void main()
{
// Seed the random number generator
srand(unsigned int(time(NULL)));
// Output 20 random numbers
for (int i = 1; i <= 20; i++)
cout << rand();
}
srand
is fed the return value of time
which
is type-casted into an unsigned integer (an integer that can't be negative)
time(NULL)
returns
the number of seconds which have elapsed since Jan 1, 1970 (this is called
Unix time)
rand
returns back a random number between 0 and RAND_MAX
(at least 32,767)
- Usually the random numbers we want to produce are bound by an upper and lower limit,
so we mod the return value from
rand
// Output 20 random numbers between 1 and 10
for (int i = 1; i <= 20; i++)
cout << rand() % 10 + 1;
- Simulate flipping a coin twenty times
for (int i = 1; i <= 20; i++)
{
// Number will be 0 or 1
if (rand() % 2 == 0)
cout << "Heads\n";
else
cout << "Tails\n";
}