C++ cstdlib rand() Function
Example
Roll a dice: get a random number from 1 to 6:
srand(time(0));
int dice = rand() % 6 + 1;
cout << dice;
Definition and Usage
The rand() function returns a random whole number from 0 to RAND_MAX. RAND_MAX is a large number, at least 32767.
Use the % (modulo) operator to get a smaller range. rand() % 6 gives a number from 0 to 5, so rand() % 6 + 1 gives a number from 1 to 6.
The rand function is defined in the <cstdlib> header file.
Note: The output is random, so it is different each time you run the program.
Tip: Call srand() once at the start of the program. Without it, rand() gives the same numbers each time the program runs. See also How To Generate a Random Number.
Syntax
int rand();
Parameter Values
None.
Technical Details
| Returns: | A random int from 0 to RAND_MAX. |
|---|