#include <iostream> #include <cstdlib> // srand and rand functions #include <ctime> // time function using namespace std; void main() { // Seed the random number generator srand(time(NULL)); // Output 20 random numbers for (int i = 1; i <= 20; i++) cout << rand(); }
time
, which
is type-casted into an unsigned integer (an integer that can't be negative)
RAND_MAX
(at least 32,767)
rand
// Output 20 random numbers between 1 and 10 for (int i = 1; i <= 20; i++) cout << rand() % 10 + 1;
for (int i = 1; i <= 20; i++) { // Number will be 0 or 1 if (rand() % 2 == 0) cout << "Heads\n"; else cout << "Tails\n"; }
srand
will result in the same numbers being
chosen every time your program runs!
srand
only needs to be called once (usually in main
).
Calling it multiple times is
unnecessary and in some cases could cause your program to choose the same random numbers
repeatedly
// Output the SAME 20 random numbers! for (int i = 1; i <= 20; i++) { srand(time(NULL)); cout << rand() % 10 + 1; }
rand
is an old C function that does not produce a uniform distribution of
random numbers, and the numbers eventually repeat
#include <random> // Create random device object random_device rd; // Create default random engine object that is seeded using random device default_random_engine engine(rd()); // Create a distribution object that has an equal chance of // returning ints between 1 and 100 (inclusive) uniform_int_distribution<int> dist(1, 100); // Get a random number using the distribution and engine objects int rand_num = dist(engine);