Send a suggestion!

We're building a brand new version of the site, and we'd love to hear your ideas

Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 52,787 times

Contents

Related Categories

Number Functions - Random Numbers

Random Numbers

You can use Rnd and Randomize to generate random numbers. The Rnd Function uses the following syntax:

Rnd()

However, the Rnd Function returns a random number less than one. So, in order to get a whole number, you need to use the Int function. If you need a larger range than 0 or 1, you need to multiply the result.

The following code simulates a dice rolling:

Randomize
Dice1 = Int(5 * Rnd) + 1
Msgbox "You rolled a " & Dice1

the statement Int(5*rnd) generates a number from 0 to 5. You add one after as you cannot role a 0. The Int statement rounds up the number from the Rnd function, as the RND function returns a number less than 1. The Randomize statement initializes the Rnd function. Without this, each time you run your application you will get the same sequence of numbers.

To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.

Comments

  • Incorrect Code

    Posted by loquin on 28 Apr 2003

    Dim sNum As String
    sNum = "Year: 2000, date: 12"
    ' Text1 will contain 200012
    Text1.Text = Val(sNum)

    This code is flat-out wrong.

    The VAL function searches the source string, converting the st...

  • I made view 10000

    Posted by HyperHacker on 01 Apr 2003

    Anywho, the last page is a bit wasteful, don't you think?
    [edit] O_o I went there again and it had gone back to 9999! Hehe, I did it twice! :p