VBA生成-35到+5之间的随机数

时间:2017-08-21 12:24:54

标签: excel vba

我正在尝试在VBA中编写一行代码,以便在-355之间生成随机数。我使用了下面的公式,它给出了-5+5之间的随机数

Int((Rnd() * ((-1) ^ Int(Rnd() * 10))) * 5)

2 个答案:

答案 0 :(得分:3)

Fix(Rnd() * 41) - 35

会做到的。在Rnd()之内,这将是均匀分布的。 Fix清除数字的小数部分。您希望每个数字在-35和5之间,包括41个数字。 rnd()本身从不画1。

之类的东西测试发生器
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

答案 1 :(得分:2)

如果您想要统一分发:

Int(Rnd*41)-35

0<=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.