Calculation of a Random Integer

Normalization. The first step in the process is to convert the integer result from rand into a floating-point number d in the half-open interval [0, 1). To do so, all you need to do is convert the result of rand to a double and then divide it by the number of elements in the range. Because RAND_MAX is often the largest integer the machine can hold, it is important to convert it to a double before adding the constant 1, which ensures that the division produces a value that is strictly less than 1.

Scaling. The second step consists of multiplying the value d by the size of the desired range, so that it spans the correct number of integers. Because the desired range includes both the endpoints, low and high, the number of integers in the range is given by the expression high – low + 1.

Truncation. The third step consists of using a type cast to convert the number back to an integer by throwing away any fraction. This step gives you a random integer with a lower bound of 0.

Translation. The final step consists of adding the value low so that the range begins at the desired lower bound.

fuente: Programming Abstractions in C++