随机数生成器在循环内运行时总是选择相同的值 [英] Random number generator always picks the same value when run inside a loop

查看:31
本文介绍了随机数生成器在循环内运行时总是选择相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码的问题是,当我尝试生成一个数字时,如果自旋等于 1,它会生成范围 (1,2,3) 内的值,如果尝试使用循环来求和相同范围内的随机值range 生成的随机数在循环中始终相同,

The problem with the code is, when I try to generate a number, if the spin is equal 1 it generates values inside range (1,2,3) if if try to use the loop to sum random values inside the same range the random number gerated is always the same while in loop,

例如,如果我使用以下命令运行循环:spind3 = 4 值从 4, 8, 12spind3 = 5 值从 5, 10, 15 开始

example, if I run the loop with: spind3 = 4 the values go from 4, 8, 12 spind3 = 5 the values go from 5, 10, 15

这意味着 RandomNumber 第一次在循环内生成一个值,它永远不会改变,直到循环完成.

That means the first time the RandomNumber generates a value inside loop, it never change until the loop completes.

if (toggled3.Checked)
   {
    if (spind3.Value != 1)
        {           
         for (int i = 1; i <= spind3.Value; i++)
              {
               diceCalc[1] += RandomNumber(1, 4);
              }
        }
     else
     diceCalc[1] = RandomNumber(1, 4);
     }

推荐答案

您可能正在 RandomNumber 方法中创建一个新的 Random 对象.Random默认构造函数 使用系统时间如种子.如果您在紧密循环中创建多个 Random 对象,则每次调用之间的时间可能不会改变,因此它们都将使用相同的种子进行初始化.

You are probably creating a new Random object inside RandomNumber method. The default constructor for Random uses the system time as a seed. If you create multiple Random objects in a tight loop the time probably won't have changed between each call so they will all be initialized with the same seed.

要修复您的代码,您应该只创建一个 Random 对象并重复使用它.

To fix your code you should only create one Random object and reuse it.

来自文档:

默认种子值来自系统时钟并且具有有限分辨率.因此,通过调用默认构造函数连续创建的不同 Random 对象将具有相同的默认种子值,因此将产生相同的随机数集.这个问题可以通过使用单个 Random 对象来生成所有随机数来避免.您还可以通过修改系统时钟返回的种子值,然后将这个新的种子值显式提供给 Random(Int32) 构造函数来解决这个问题.有关详细信息,请参阅 Random(Int32) 构造函数.

The 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. This problem can be avoided by using a single Random object to generate all random numbers. You can also work around it by modifying the seed value returned by the system clock and then explicitly providing this new seed value to the Random(Int32) constructor. For more information, see the Random(Int32) constructor.

这篇关于随机数生成器在循环内运行时总是选择相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆