-2

I am wondering on how I can prevent a Randomize() function from returning a value less than 0. Thanks!

  • I'm a bit confused by this question. The Visual Basic subroutine Randomize doesn't return any value at all. It's used to seed the random number generator. The Rnd function is used to return random numbers, but by definition it only returns values between zero (inclusive) and one (exclusive). Can you give an example of where you're using randomization in your game and having a problem with negative return values? – DMGregory Apr 22 '17 at 23:34

2 Answers2

1

You could do it with a range:

CInt(Math.Ceiling(Rnd() * n)) + 1

or

Dim Generator As System.Random = New System.Random()
Dim rndValue As Integer = Generator.Next(min, max)

or you could just use the abs always, so every negative number would turn into the positive counterpart.

Artery
  • 194
  • 2
  • 10
  • Okay, but I need it to not go past 0 like if the current number value was 8 and it then returns a value of 9, that would then be -1. Here is the code to better understand.

    damage = ((frmMainGame.lblInfantryNumberAI.Text * Rnd()) + 1) <--- it can not go past 0. Once it is at 0, it no longer returns a value except 0

    – Captain Caboose Nov 08 '16 at 02:43
  • I am not getting what you mean, take a look at the link. – Artery Nov 08 '16 at 03:05
  • Accidentally posted that comment :D I would suggest to use the generator, I edited this into my answer. That works fine. – Artery Nov 08 '16 at 03:06
-2

You can use this function

Function Rand(Low as Long, High as Long) As Long 
   Return Random.Next(Low, High) 
End Function