我需要生成一个介于1和n(其中n是正整数)之间的随机整数,以用于单元测试。我不需要过于复杂的东西来确保真正的随机性--只需要一个老式的随机数即可。
我该怎么做呢?
发布于 2008-08-20 19:55:54
要获得一个介于1和N(包括1和N)之间的随机整数值,可以使用以下命令。
CInt(Math.Ceiling(Rnd() * n)) + 1
发布于 2010-04-21 02:57:37
正如已经多次指出的,建议编写这样的代码是有问题的:
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
Dim Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max)
End Function
原因是Random
类的构造函数提供了基于系统时钟的默认种子。在大多数系统上,这是有限的粒度--大约在20ms左右。所以,如果你写了下面的代码,你将会连续得到相同的数字:
Dim randoms(1000) As Integer
For i As Integer = 0 to randoms.Length - 1
randoms(i) = GetRandom(1, 100)
Next
下面的代码解决了这个问题:
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
' by making Generator static, we preserve the same instance '
' (i.e., do not create new instances with the same seed over and over) '
' between calls '
Static Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max)
End Function
我拼凑了一个简单的程序,使用这两种方法生成了25个介于1和100之间的随机整数。下面是输出:
Non-static: 70 Static: 70
Non-static: 70 Static: 46
Non-static: 70 Static: 58
Non-static: 70 Static: 19
Non-static: 70 Static: 79
Non-static: 70 Static: 24
Non-static: 70 Static: 14
Non-static: 70 Static: 46
Non-static: 70 Static: 82
Non-static: 70 Static: 31
Non-static: 70 Static: 25
Non-static: 70 Static: 8
Non-static: 70 Static: 76
Non-static: 70 Static: 74
Non-static: 70 Static: 84
Non-static: 70 Static: 39
Non-static: 70 Static: 30
Non-static: 70 Static: 55
Non-static: 70 Static: 49
Non-static: 70 Static: 21
Non-static: 70 Static: 99
Non-static: 70 Static: 15
Non-static: 70 Static: 83
Non-static: 70 Static: 26
Non-static: 70 Static: 16
Non-static: 70 Static: 75
发布于 2008-08-20 20:00:03
Dim MyMin As Integer = 1, MyMax As Integer = 5, My1stRandomNumber As Integer, My2ndRandomNumber As Integer
' Create a random number generator
Dim Generator As System.Random = New System.Random()
' Get a random number >= MyMin and <= MyMax
My1stRandomNumber = Generator.Next(MyMin, MyMax + 1) ' Note: Next function returns numbers _less than_ max, so pass in max + 1 to include max as a possible value
' Get another random number (don't create a new generator, use the same one)
My2ndRandomNumber = Generator.Next(MyMin, MyMax + 1)
https://stackoverflow.com/questions/18676
复制相似问题