Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Random Function?
#1
Ok i was wondering if there is a function or how to make a function where itll pick a random number between a predetermined high and low number?

so like youd call
Code:
Rand(3 'High num, 1 'Low num)
Reply
#2
I'm unfamiliar with all the math functions in vb, but I'm good with theory.

I think it should be something like

function RandRange(ByVal Low As Long,ByVal High As Long) As Long
Rand = int((High - Low + 1) * "random number") + Low
end function

somethin like that. look up the random function and replace "random number" with it.
Reply
#3
Code:
Dim MyValue
MyValue = Int((6 * Rnd) + 1)   ' Generate random value between 1 and 6.
Reply
#4
Dragoons Master Wrote:
Code:
Dim MyValue
MyValue = Int((6 * Rnd) + 1)   ' Generate random value between 1 and 6.

That wouldn't work. if Rnd turned out to be .9, then MyValue would equal 7.

Here's a working function.
Function Rand(ByVal Low As Long, ByVal High As Long) As Long
Rand = Int((High - Low + 1) * Rnd) + Low
End Function
Reply
#5
sweet thanks asrrin (woot i spelled it right Tongue), dragoons master's kinda worked. you could have a high but there wouldnt be a low number to put into it.

thanks everyone
Reply
#6
seraphelic Wrote:
Dragoons Master Wrote:
Code:
Dim MyValue
MyValue = Int((6 * Rnd) + 1)   ' Generate random value between 1 and 6.

That wouldn't work. if Rnd turned out to be .9, then MyValue would equal 7.

Here's a working function.
Function Rand(ByVal Low As Long, ByVal High As Long) As Long
Rand = Int((High - Low + 1) * Rnd) + Low
End Function
Actualy... no, Int(6*0,9)+1 = 6
I got that example from MSDN, so it actually can't be wrong...
But for any range:
Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
Also got it from MSDN.
I miss read the first example.
Reply
#7
My fault, I misinterpreted Int().
Reply
#8
No return type?
Reply
#9
Dave Wrote:Function Random(Lowerbound As Integer, Upperbound As Integer) as Integer

Dragoons Master Wrote:No return type?

?
Reply
#10
GIAKEN Wrote:
Dave Wrote:Function Random(Lowerbound As Integer, Upperbound As Integer) as Integer

Dragoons Master Wrote:No return type?

?
Not this one:
Code:
A six second google returned this:

Code: Select all
    Function Random(Lowerbound As Long, Upperbound As Long)
    Randomize
    Random = Int(Rnd * Upperbound) + Lowerbound
    End Function
Reply
#11
hmmm mk. well im not using MS. but it works and thats good enough for me. at least for now.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)