Generating Random Numbers

Visual Basic .NET provides exactly one random number generator, a function named Rnd() that returns a pseudo-random Double between 0 and 1. After the following statements execute, the dblWhoKnows variable contains a random number between 0 and 1:

Dim dblWhoKnows As Double
dblWhoKnows = Rnd()

If you need random numbers in a different range, such as 25 to 75, just multiply the Rnd() result by the difference and add the starting value. In the following expression, (Rnd() * 50) returns a random number between 0 and 50. Adding an offset of 25 makes the complete expression return a value in the desired range:

25 + (Rnd() * 50)

The Rnd() function never returns a result of exactly 0 or exactly 1. As a result, the expression

Int(Rnd() ...

Get Faster Smarter Beginning Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.