【问题标题】:Why do both of the random numbers I create be the same everytime in visual basic?为什么我在 Visual Basic 中创建的两个随机数每次都相同?
【发布时间】:2016-12-26 15:25:55
【问题描述】:

为什么每次运行代码时 RandomInt1 和 RandomInt2 总是相同的数字?

    Dim RandomGen1 As New Random
    Dim RandomInt1 As Integer
    RandomInt1 = RandomGen1.Next(2, 7)

    Dim RandomGen2 As New Random
    Dim RandomInt2 As Integer
    RandomInt2 = RandomGen2.Next(2, 7)

【问题讨论】:

  • 与你的问题无关,但是当你发现自己对很多相关变量做同样的事情时,你应该考虑使用数组或其他一些数据结构。

标签: vb.net random integer


【解决方案1】:

令人兴奋的有趣事实:计算机中没有truly 随机数之类的东西,.NET 框架对这个概念的实现与您的问题有关。

当您使用 .NET 启动程序时,您创建的每个随机数生成器(在给定范围内)都会产生相同的数字序列。当您的程序启动时,您将获得的结果序列已经由实例以某种方式选择的种子确定。以此种子开始的任何随机化都会产生相同的数字序列。这是命运。

解决方案是只使用一个“生成器”(或“命运处理器”),并在需要新号码时继续调用.Next 方法。你的项目听起来很酷,但我编辑了你的帖子以尽可能清晰。祝你好运:

    Dim RandomGen1 As New Random
    Dim RandomInt1 As Integer
    RandomInt1 = RandomGen1.Next(2, 7)

    'notice I did not make a RandomGen2, it will just give me the same numbers as RandomGen1
    Dim RandomInt2 As Integer
    RandomInt2 = RandomGen1.Next(2, 7)

【讨论】:

  • 从技术上讲,数字不是预先确定的,没有返回的数字大文件或数据库。它们只是在数学上以始终从给定种子返回相同序列的方式生成。
  • 好的,它们是由公式和种子决定的?预先确定的?来吧:)srsly
  • 在程序启动时,数字的顺序并不总是已知的。种子可以通过诸如计时器之类的源或用户输入以编程方式提供。
  • 我想了一下你说的,我想我同意你现在说的。你是对的,它没有存储在内存中,它还没有计算出来。它必须被请求。它是确定的,但不是预先确定的。它更像是命中注定。
  • 来自MSDNThe default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多