首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >VB.NET中的随机整数

VB.NET中的随机整数
EN

Stack Overflow用户
提问于 2008-08-20 19:54:00
回答 11查看 350.5K关注 0票数 65

我需要生成一个介于1和n(其中n是正整数)之间的随机整数,以用于单元测试。我不需要过于复杂的东西来确保真正的随机性--只需要一个老式的随机数即可。

我该怎么做呢?

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2008-08-20 19:55:54

要获得一个介于1和N(包括1和N)之间的随机整数值,可以使用以下命令。

代码语言:javascript
复制
CInt(Math.Ceiling(Rnd() * n)) + 1
票数 66
EN

Stack Overflow用户

发布于 2010-04-21 02:57:37

正如已经多次指出的,建议编写这样的代码是有问题的:

代码语言:javascript
复制
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左右。所以,如果你写了下面的代码,你将会连续得到相同的数字:

代码语言:javascript
复制
Dim randoms(1000) As Integer
For i As Integer = 0 to randoms.Length - 1
    randoms(i) = GetRandom(1, 100)
Next

下面的代码解决了这个问题:

代码语言:javascript
复制
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之间的随机整数。下面是输出:

代码语言:javascript
复制
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
票数 80
EN

Stack Overflow用户

发布于 2008-08-20 20:00:03

使用System.Random

代码语言:javascript
复制
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)
票数 35
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档