[RESOLVED] Random Number Problem
Here is my function for generating a random number:
Code:
Public Function GenRandomNo(ByVal MinValue As Integer, ByVal MaxValue As Integer) As Integer
Dim RndInst As New Random 'Create New Random'
GenRandomNo = RndInst.Next(MinValue, MaxValue) 'Generate Random Integer Between The Min And Max Value'
End Function
And here is where I am using it:
Code:
Public Function CheckPowerUp() As Boolean
Dim RndNo As Integer = GenRandomNo(1, 5) 'Generate A Number Between 1 and 5'
Select Case RndNo 'Check Generated Number, Return True If Number Is 5'
Case 1
Return False
Case 2
Return False
Case 3
Return False
Case 4
Return False
Case 5
Return True
End Select
End Function
I have put a breakpoint and created a test log and for some reason it is never generating a 5 only 1 to 4. Any ideas why this could be happening?
Re: Random Number Problem
Have you read the documentation of the Random class, espcially the Next method?
I guess not.... To generate a random number between 1 and 5 inclusive, you need to do random.Next(1, 6)
Re: Random Number Problem
this:
Code:
GenRandomNo(1, 5) 'Generate A Number Between 1 and 5'
means: Generate number that equal to 1 and less then 5, change the 5 to 6 and you ready to go :)
Re: Random Number Problem
The random object generates from MinValue to MaxValue - 1. Therefore, (1,5) will generate 1-4, not 1-5.
By the way, since you are creating the Random object in the sub, if you call that sub in a loop, your numbers will not be random at all. In fact, they will be a series of the same number if the loop is fast enough. The reason is that the random number generator is seeded on the current time. If the call to the sub is made fast enough, the time will be the same for subsequent calls. Random objects created with the same seed will return the same value.
To solve this, declare a single Random object at class or form scope and use that repeatedly, rather than creating one within a sub.
Re: Random Number Problem
I didn't expect to be the first to answer that, but I didn't expect TWO people to get in ahead of me. However, I added a little extra value to my answer.
Re: Random Number Problem
Ok thanks for the help I think Ill declare the random once aswell as Im using XNA and the loop is at least 20fps so this will prob end up causing me some problems.
Thanks again
Re: [RESOLVED] Random Number Problem
Yes, it certainly would cause issues. Your random would not be.