There are many times in computer programs that we want to introduce some kind of random behaviour. This could be for randomly generated levels in a game, random motion for some kind of a simulation, or to choose random questions for a quiz program.
Unfortunately, computers can't make truly random choices; everything a computer does is based on calculations. However, computers can generate pseudo-random numbers; numbers that technically follow a pattern, but the pattern is almost impossible to figure out.
To generate a pseudo-random number in Visual Basic, there are two steps:
1. Create a variable of type "Random"
2. Use one of the following commands to generate your random number:
(Assume that rand has been declared as a variable of type “Random”)
rand.Next() – Generate a random integer between 0 and the maximum possible integer value
rand.Next( a ) – Generate a random integer that is >= 0 and < a
rand.Next( a, b ) – Generate a random integer that is >= a and < b
rand.NextDouble() – Generate a random number that is >= 0.0 and < 1.0
For example, the following program simulates rolling a pair of dice:
Dim rand as Random
Dim iDie1, iDie2, iDieTotal as Integer
rand = New Random
iDie1 = rand.Next(1, 7)
iDie2 = rand.Next(1, 7)
iDieTotal = iDie1 + iDie2
Create math quiz program, similar to the following: see image.
Your program should: