mercredi 12 juin 2019

Is there a way to generate a random number using a Minimum and Maximum value using Single in VB.Net?

I'm looking for a random number generator that I can use to alter the size of a picture box on my form. Currently, I have this solution found here on StackOverflow:

    Public Function GetRandomNumber(ByVal Min As Integer, ByVal Max As Integer) As Integer
        Static lcGenerator As System.Random = New System.Random()
        Return lcGenerator.Next(Min, Max)
    End Function

As it stands, the function will generate a random integer between the range specified. This is great, but I am noticing that often the picture box doesn't change in size with a decent amount of variation. The following code shows how I am calculating variance in size:

Dim lcModifier As Decimal = (GetRandomNumber(-20, 11) * 0.01)

pbForeground.Width = CInt((0.4 - lcModifier) * pbBackground.Width)
pbForeground.Height = CInt((0.4 - lcModifier) * pbBackground.Height)

The idea is that I generate a random number between -20 and 11. This would yield a 20% increase or 10% decrease, as the minimum is inclusive but the maximum is exclusive, and I am subtracting the modifier.

I had the idea to use a Single value in place of the integer value. The Single type gave me more "room" away from 0 than a Double would, but the Next method only uses Integer values, and we're back to my initial problem.

The NextDouble method works differently to the Next method, and I am unable to specify Min and Max values, nor can I generate a negative value.

Is there any way I can generate a value using Minimum and Maximum bounds that is not close to zero?

Thanks, sunnyCr




Aucun commentaire:

Enregistrer un commentaire