The million dollar question...
... or the most commonly asked question is : "How can I generate a number between 2 other numbers?"
The main problem with this is that many people haven't realised that the Rnd function returns a value less than 1 BUT greater than or equal to zero (0<=Rnd<1). So since most people think that the Rnd function can generate the number 1, the algorithms they use are incorrect. The correct way is this :
VB Code:
Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
Which can easily be put into a function :
VB Code:
Private Function RandomInteger(Lowerbound As Integer, Upperbound As Integer) As Integer RandomInteger = Int((Upperbound - Lowerbound + 1) * Rnd + Lowerbound) End Function
and an example of using it is :
VB Code:
Private Function RandomInteger(Lowerbound As Integer, Upperbound As Integer) As Integer RandomInteger = Int((Upperbound - Lowerbound + 1) * Rnd + Lowerbound) End Function Private Sub Form_Load() Randomize 'Just once to start getting random numbers MsgBox RandomInteger(1, 52) End Sub
The code above would be used most of the times for a card game, to draw a card at random. If we set Lowerbound=1 and Upperbound=6 then we would have ourselves dice rolling code![]()




Reply With Quote