Visal Basic per Begginer

Page 132

113

LiRandomNumber = Int(6 * Rnd) + 1

Chapter 4

I had to add 1 to the equation to get numbers from 1 to 6. This is because the rnd function generates numbers from 0 to 1, but not including 1. So if I did not include the addition of 1 to the equation, I would get random numbers in the range of 0 to 5.

Iteration

Because these numbers are real numbers (decimals or fractions) and not integers, you need to perform a little Visual Basic trickery to get whole numbers such as 1, 2, 3, 4, 5, or 6. For example, the following statement generates a random number from 1 to 6 and assigns it to an integer variable:

Also, I enclose the rnd function in the int function. Enclosing a non-integer number in the Int() function ensures that you get an integer number. The rnd function generates a seemingly random pattern the more it is executed. However, you will find that when first executed, the rnd function starts with the same number each time. To solve this problem, Visual Basic provides another function called randomize.

Randomize Function The randomize function uses your computer’s internal clock to assist you in generating random numbers. If your program includes the randomize function, the rnd function generates a more varied number each time it is first executed. The randomize function requires no parameters and must be called only once in your program. For example, you can put the randomize function in your form’s load event: Private Sub Form_Load() Randomize End Sub

To illustrate the use of random numbers, I show you a small program I wrote called dice in Figure 4.3. My dice program uses a number of Visual Basic fundamentals that you have already learned so far in this book. Specifically, it uses image swapping, a timer control, select case structures, if conditions, and random numbers. HIN

T

The dice images used in the dice program were created by For the Absolute Beginner series editor Andy Harris and appear in this book’s accompanying CD-ROM.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.