Games
Problems
Go Pro!

# Random Number Generators

Reference > Science > Technology > Beginner Programming Tips

The first programs I ever wrote were games. They were silly games, and nobody but me wanted to play them, but they were definitely good programming experience. Of course, if you are writing a game program, you need to generate random numbers, otherwise the game gets quite tedious, doing the same thing over and over and over...

So I very quickly discovered this little snippet of code, and used it extensively without ever bothering to look at what was actually happening "behind the scenes."

Dim MyRandomNumber As Integer

'Pick A Random Number Between 1 and 10 Inclusive
âMyRandomNumber = Int(Rnd * 10) + 1

Here is what's happening. "Rnd" is the actual Random Number Generator. What does it generate? It generates a Random number between 0 and 1, possibly including 0, but never including 1. So when you multiply it by ten, you get a number which is somewhere between zero and ten. Possibly including 0, but never including ten.

And here comes the handy math function "Int," which takes the integer part of a decimal value. For example, the integer part of 2.3 is 2. The integer part of 6.9 is 6.

So when you take the integer part of your random number times ten, you get any integer from zero to nine, but not ten. Thus, to get a random number between one and ten, you just need to add one to your random number.

Now take a look at this piece of code:

Dim MyRandomNumber As Integer

'Pick A Random Number Between 5 and 9 Inclusive
âMyRandomNumber = Int(Rnd * 5) + 5

Do you see what's happening here? If you are looking for a random number between five and ten, you have five possible values (5, 6, 7, 8, and 9). So you have to multiply the random generator by five. Of course, that just gives you the following values: 0, 1, 2, 3, or 4. So you need to add five to get the values you want.

Want to try another one? Let's say you want the computer to pick a random multiple of 5 between 0 and 50 inclusive. Here's the code for it; see if you can figure out why it works. And when you've done that, try some of the Other Scenarios listed below.

Dim MyRandomNumber As Integer

'Pick A Random Multiple of 5, between 0 and 50
âMyRandomNumber = 5* Int(Rnd * 11)

## Questions

1.
What numbers could be generated by this line of code: MyRandomNumber = Int(Rnd * 4) + 3?
2.
What numbers could be generated by this line of code: MyRandomNumber = 2 * Int(Rnd * 5) - 2?
3.
What numbers could be generated by this line of code: MyRandomNumber = 5 * Int(Rnd * 3)?
4.
Write a line of code to generate a random number between one and fifty, inclusive.
5.
Write a line of code to generate a random number between seven and twenty, inclusive.
6.
Write a line of code to generate an even random number between two and ten, inclusive. Assign this reference page Bit Toggle Treating Equations as Values    Like us on Facebook to get updates about new resources