I am using the following code in the Load method of a VB form to generate random numbers in the range 1 to 8. Without fail after enough loops the range is exceeded and 9 is the random number returned every time. The line using the Rnd function is from:
Rnd Function (Visual Basic)
Randomize()
Dim LoopCount As Integer = 0
Do
GoldButtonNumber = CInt(Int((8 * Rnd()) + 1))
LoopCount += 1
Loop Until GoldButtonNumber > 8
From the documentation it makes sense to me as the Rnd number generated could be less than, but very close to 1, which when multiplied by 8 will be very close to 8. It will be rounded up to 8 when converted to an integer and when 1 is added will be 9. What am I missing?
Thanks,
Rosemary
Rnd Function (Visual Basic)
Randomize()
Dim LoopCount As Integer = 0
Do
GoldButtonNumber = CInt(Int((8 * Rnd()) + 1))
LoopCount += 1
Loop Until GoldButtonNumber > 8
From the documentation it makes sense to me as the Rnd number generated could be less than, but very close to 1, which when multiplied by 8 will be very close to 8. It will be rounded up to 8 when converted to an integer and when 1 is added will be 9. What am I missing?
Thanks,
Rosemary