VBA生成-35到+5之间的随机数字
我想在VBA中编写一行代码,这将允许我在-35
和5
之间生成随机数字。 我已经使用了下面的公式,它给了我-5
到+5
之间的随机数
Int((Rnd() * ((-1) ^ Int(Rnd() * 10))) * 5)
Fix(Rnd() * 41) - 35
会做的。 就Rnd()
,这将是均匀分布的。 Fix
磨擦数字的小数部分。 你希望每个数字在-35和5之间,这是41个数字。 rnd()
本身从不绘制1。
用类似的东西testing发电机
Sub test() Dim j As Long While True j = Fix(Rnd() * 41) - 35 VBA.DoEvents 'so you can break the program once you're done If j < -35 Or j > 5 Then Stop 'oops End If If j = -35 Then Debug.Print "Yup, I draw on the boundary" End If If j = 5 Then Debug.Print "Yup, I draw on the boundary" End If Wend End Sub
如果你想要一个统一的分配:
Int(Rnd*41)-35
0<=Rnd<1
( Rnd=1
我发现Rnd=1
,但是接缝不再发生)
0<=Rnd*41<41
0<=Int(Rnd*41)<=40
-35<=Int(Rnd*41)-35<=5
从文档:
Int Returns the integer portion of a number.