下面这个函数,可以生成一定范围内的随机数,可以指定小数位数。
比如 RndBetween (10, 99, 2) 返回 [10.00~99.00] 范围内的随机数。
Function RndBetween(ByVal Lowbound As Long, ByVal Upbound As Long, Optional ByVal Dcml As Integer = 0) As Double
‘参数分别是:下限,上限,小数位数(默认值是0,没有小数部分)
‘参数过大可能发生溢出错误
‘生成指定范围内(含上下边界)的整数: _
Int((upperbound – lowerbound + 1) * Rnd + lowerbound)
‘多次调用本函数时,允许生成相同的数,但不会生成可重复产生的序列
‘最近一次修改:2016-4-27
Static I As Long
I = I + 1
Dim Temp As Long
If Upbound < Lowbound Then
Temp = Upbound
Upbound = Lowbound
Lowbound = Temp
End If
If Dcml < 0 Then Dcml = 0
If Dcml > 255 Then Dcml = 255
‘实际上只生成十几位有效数字,除非改用字符连接等方法
Randomize (Timer + I)
‘ If Dcml = 0 Then
‘ RndBetween = Int((Upbound – Lowbound + 1) * Rnd + Lowbound)
‘ Else
‘ RndBetween = Int((Upbound * 10 ^ Dcml – Lowbound * 10 ^ Dcml + 1) * Rnd + Lowbound * 10 ^ Dcml) / 10 ^ Dcml
‘ End If
‘强制转换类型,避免在上下限相差过大时可能发生溢出错误
If Dcml = 0 Then
RndBetween = Int((CDbl(Upbound) – CDbl(Lowbound) + 1) * Rnd + CDbl(Lowbound))
Else
RndBetween = Int((CDbl(Upbound) * 10 ^ Dcml – CDbl(Lowbound) * 10 ^ Dcml + 1) * Rnd + CDbl(Lowbound) * 10 ^ Dcml) / 10 ^ Dcml
End If
End Function