2. The Visual Basic Language
A Closer Look at the Rnd Function
- In writing games and learning software, we use the Rnd
function to introduce randomness. This insures different results
each time you try a program. The Visual Basic function Rnd returns
a single precision, random number between 0 and 1 (actually greater
than or equal to 0 and less than 1). To produce random integers (I)
between Imin and Imax, use the formula:
I = Int((Imax - Imin + 1) * Rnd) + Imin
- The random number generator in Visual Basic must be seeded.
A Seed value initializes the generator. The Randomize statement
is used to do this:
If you use the same Seed each time you run your application,
the same sequence of random numbers will be generated.
To insure you get different numbers every time you use your
application (preferred for games), use the Timer function
to seed the generator:
Place this statement in the Form_Load event procedure.
- Examples:
To roll a six-sided die, the number of spots would be computed using:
NumberSpots = Int(6 * Rnd) + 1
To randomly choose a number between 100 and 200, use:
Number = Int(101 * Rnd) + 100
Counter Hit
This Homepage is special brought to you by CK Tan