Reputation: 57
I am working on a project for a intro VB class. I need to create a random number between 2 values the user enters. I have an upper limit textbox/variable and a lower limit textbox/variable. I have tried everything I could find and it produces weird results. I can't figure out how to get the random numbers generated between 2 values. For example if the user enters 100 for the lower limit and 500 for the upper limit the random should be in the range of 100-500.
Please let me know what I am doing wrong??
'Grabs the txbox input and assigns to vars
intLowNumber = CInt(mskLowerRange.Text)
intUpperNumber = CInt(mskUpperRange.Text)
intRandomNumber = rand.Next(intUpperNumber) - intLowNumber
'Output to listbox and textbox
lstOutput.Items.Add(intRandomNumber)
txtNumber.Text = CStr(intRandomNumber)
Upvotes: 0
Views: 20715
Reputation: 7676
Your code is wrong, specifically
intRandomNumber = rand.Next(intUpperNumber) - intLowNumber
Say intUpperNumber
is 200 and intLowNumber
is 100, the above gives somewhere between -100 (0 - 100) and 99 (199 - 100).
You can give Random.Next two parameters for a random number in a range. The first parameter is the minimum value and the second parameter is the maximum value of the random number.
Note that the upper bound (the maximum value) is exclusive, so if you want to include the highest value you need to add 1. Use it like this:
'Grabs the txbox input and assigns to vars
intLowNumber = CInt(mskLowerRange.Text)
intUpperNumber = CInt(mskUpperRange.Text)
intRandomNumber = rand.Next(intLowNumber, intUpperNumber+1)
'Output to listbox and textbox
lstOutput.Items.Add(intRandomNumber)
txtNumber.Text = CStr(intRandomNumber)
Upvotes: 4