Results 1 to 10 of 10

Thread: Easy Random Number Function (Min, Max & Round)

Threaded View

  1. #1

    Thread Starter
    No place like 127.0.0.1 eyeRmonkey's Avatar
    Join Date
    Jul 2005
    Location
    Blissful Oblivion
    Posts
    2,306

    Easy Random Number Function (Min, Max & Round)

    This functions makes getting random whole/decimal numbers easy. It also automatically calls Randomize the first time the function is called, so there is no need to put it in the Form_Load Procedure.
    VB Code:
    1. ' Place this code in a module.
    2. ''''''''''''''''''''''''''''''''''
    3. ' Date:         7/2/2005         '
    4. ' Last Update:  7/29/2005        '
    5. ' Author:       Jeremy Blanchard '
    6. ''''''''''''''''''''''''''''''''''
    7. Option Explicit
    8.  
    9. Public Function Rand(Max As Double, _
    10.             Optional Min As Double = 0, _
    11.             Optional NumDigitsAfterDecimal As Integer = 0) As Double
    12.   ' Returns a pseudo-random number  between 'Min' and 'Max'.
    13.   '   Calls Randomize the first time the function is called.
    14.  
    15.     Static sbRandomized As Boolean
    16.     Dim r As Double
    17.  
    18.     If Not sbRandomized Then
    19.         Randomize
    20.         sbRandomized = True
    21.     End If
    22.  
    23.     If NumDigitsAfterDecimal <= 0 Then
    24.         Rand = Int(Rnd * (Max - Min + 1)) + Min
    25.     Else
    26.         ' Less accurate number distrubtion because of decimals.
    27.         Rand = Round((Rnd * (Max - Min)) + Min, NumDigitsAfterDecimal)
    28.     End If
    29. End Function
    VB Code:
    1. ' Example uses
    2.   ...
    3.   r = Rand(255)
    4.   g = Rand(255)
    5.   b = Rand(255)
    6.   Form1.BackColor = RGB(r, g, b)   ' Random background color
    7.   ...
    8.   iMyNum = Rand(10, -10, 3)  ' Rounded to 3 decimal places
    NOTE: Update on 7/29/05 switched max to the first parameter and Min to the second (and made it default optional).

    Let me know if you like this module or used it in a cool way.
    Last edited by eyeRmonkey; Jul 29th, 2005 at 09:46 PM. Reason: Modifications to module
    Visual Studio 2005 Professional Edition (.NET Framework 2.0)
    ~ VB .NET Links: Visual Basic 6 to .NET Function Equivalents (Thread) | Refactor! (White Paper) | Easy Control for Wizard Forms | Making A Proper UI For WinForms | Graphics & GDI+ Tutorial | Websites For Free Icons
    ~ QUOTE: Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. -Rich Cook

    ~ eyeRmonkey.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width