Random Numbers

Random Numbers

Random numbers are useful in many situations, not just games, but also in serious applications such as simulations, educational software and others.

The statement r= rand(); assigns a random value to r.

The table below shows the transformation of a random number to a random value from 1 to 6:

r = rand(); r = r % 6; r = r + 1;
4896 0 1
1259 5 6

r%6 will result in a value from 0 to 5, adding 1 givers us the values from 1 to 6.

Instead of doing this step-by-step as shown above the following statement can be used:
r=rand() % 6 + 1;

A general rule is to get the remainder after dividing by the number of values in the range and then add the lowest value in the range.
The script below will allows you to enter the first and last values and see the C++ statement to compute the random numbers. Press enter after adding the values.

Put in the first and last values

first last

NEXT: Rolling dice