< Previous | Contents | Next >

Calculating a Number within a

Range

After generating a random number, randomNumber holds a value between 0 and 32767 (based on my implementation of C++). But I need a number between 1 and 6, so next I use the modulus operator to produce a number in that range.

int die = (randomNumber % 6) + 1; // get a number between 1 and 6

Any positive number divided by 6 will give a remainder between 0 and 5. In the preceding code, I take this remainder and add 1, giving me the possible range of 1 through 6exactly what I wanted. You can use this technique to convert a random number to a number within a range youre looking for.

72 Chapter 2 n Truth, Branching, and the Game Loop: Guess My Number


Tra p

image

Using the modulus operator to create a number within a range from a random number might not always produce uniform results. Some numbers in the range might be more likely to appear than others. However, this isn’t a problem for simple games.

image