Call to Rnd() generating the same number

前端 未结 3 1597
感动是毒
感动是毒 2020-12-06 18:51

When I set up this bit of code, every time I debug the software it generates the same number. Can anyone tell me why this is happening?

dim value as integer
         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 19:06

    The reason you get the same random number each time is that when the program runs, it always starts with the same seed number for generating the first random number. To change the seed, you can add this ..

    Randomize()
    

    into your code's _load event. This changes the seed based on the time.

    Alternatively, you could use the following code as this doesn't need to call 'Randomize' each time the program is run, and it is much easier to control the range of numbers generated. For example instead of random numbers in the range of 0 to 100 as per the code below, you could choose to generate numbers from 45 to 967 or any other range you like, just by changing the parameters of the second line.

    Dim randomGenerator As New Random 'add this to the beginning for your Form1 class
    value =randomgenerator.Next(0,100) 'add this into your methods as needed
    Messagebox.Show(value)
    

    Its probably better to declare randomGenerator as project wide variable rather than keep re-declaring it in a code block - This is because it uses the time as the seed.

    If the declaration is in a tight loop that iterates over small intervals of time, the seed might sometimes be the same for each time the variable is declared and you could end up with the same number being generated multiple times. For example - This is how not to do it :-

    For i As Integer = 1 To 1000
        Dim a As New Random
        Console.WriteLine(a.Next())
    Next
    

提交回复
热议问题