在 VB.NET 中在 Rnd() 之前使用 Randomize()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1380990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Randomize() before Rnd() in VB.NET
提问by Cyclone
I have previously been told that I should always use Randomize()
before I use Rnd()
in a VB.NETapplication. Yet, it always seems to work fine without it. What does adding Randomize()
do for me in this case?
之前有人告诉Randomize()
我Rnd()
,在VB.NET应用程序中使用之前,我应该始终使用它。然而,如果没有它,它似乎总是能正常工作。Randomize()
在这种情况下,添加对我有什么作用?
It doesn't appear to affect my application in the least.
它似乎至少不会影响我的申请。
回答by Philip Rieck
In Visual Basic, Rnd() uses a mathematical operation to produce the next "random" number. Because the actual operation is known, given a specific value, you can predict the next value. However, given an arbitray start value the numbers have good distribution - these are "pseudo-random" numbers.
在 Visual Basic 中,Rnd() 使用数学运算来产生下一个“随机”数。因为实际操作是已知的,给定一个具体的值,就可以预测下一个值。然而,给定一个任意的起始值,这些数字具有良好的分布——这些是“伪随机”数字。
To keep Rnd()
from startng at a predictable number (and hence giving the same sequence of "random" numbers every time), Randomize() should be called to use the machine clock to set the initial value (called a seed).
为了Rnd()
避免从可预测的数字开始(因此每次都给出相同的“随机”数字序列),应该调用Randomize() 以使用机器时钟来设置初始值(称为种子)。
(In the .NETworld, I'd use System.Randominstead if you can.)
(在.NET世界中,如果可以的话,我会改用System.Random。)
回答by Eran Betzalel
Randomize()
initializes the first seed of Rnd()
. If you won't use it - VB.NET will use the default seed number.
Randomize()
初始化 的第一个种子Rnd()
。如果您不使用它 - VB.NET 将使用默认种子编号。
回答by Rodrigo
Randomize will set the seed to something time related, like the system uptime or the system date. So the function Rand()
will show different values every time the app is executed. However, I highly recommend you to use the System.Random class instead of VisualBasic Rand()
. No need to call any randomize()
function
Randomize 会将种子设置为与时间相关的内容,例如系统正常运行时间或系统日期。因此,Rand()
每次执行应用程序时,该函数都会显示不同的值。但是,我强烈建议您使用 System.Random 类而不是 VisualBasic Rand()
。无需调用任何randomize()
函数
Here are some example code, this will generate six random integers from the lower to upper bounds:
下面是一些示例代码,这将生成从下限到上限的六个随机整数:
Dim randObj As New Random( seed )
Dim j As Integer
For j = 0 To 5
Console.Write( "{0,11} ", randObj.Next( lower, upper ) )
Next j
Console.WriteLine( )