在循环中运行时,随机数发生器总是选择相同的值 [英] Random number generator always picks the same value when run inside a loop
问题描述
与代码的问题是,当我尝试生成一个号码,如果自旋等于1它产生的范围内(1,2,3)如果要是尝试使用循环来总结里面相同的随机值的值范围gerated随机数始终是相同的,而在循环,
例如,如果我运行的循环:
spind3 = 4的值从4去, 8,12
spind3 = 5的值从5走,10,15
这意味着第一次RandomNumber产生内部循环的值,它永远不会改变直到循环完成。
如果(toggled3.Checked)
{
如果(spind3.Value! = 1)
{
的for(int i = 1; I< = spind3.Value;我++)
{
diceCalc [1] + = RandomNumber(1,4) ;
}
}
,否则
diceCalc [1] = RandomNumber(1,4);
}
您可能正在创建一个新的随机
RandomNumber
方法内的对象。为随机默认构造函数
使用系统时间作为种子。在紧密循环如果创建了多个随机
对象的时候可能不会每次通话,使他们都将使用相同的种子进行初始化之间改变。
要修复您的代码,你应该只创建一个随机
对象,然后重新使用。
从文档:
默认种子值是从系统时钟产生,并具有有限的分辨率。作为结果,在接近连续通过向默认构造函数的调用创建不同的
随机
对象将具有相同的默认种子值,因此,会产生随机数套相同。可以通过使用单个随机
对象生成所有随机数来避免此问题。您也可以通过修改系统时钟返回的种子值,然后明确地提供这种新的种子值的随机(Int32)已
构造解决它。有关详细信息,请参阅随机(Int32)已
构造。
块引用>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,
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
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); }
解决方案You are probably creating a new
Random
object insideRandomNumber
method. The default constructor forRandom
uses the system time as a seed. If you create multipleRandom
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.To fix your code you should only create one
Random
object and reuse it.
From the documentation:
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 singleRandom
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 theRandom(Int32)
constructor. For more information, see theRandom(Int32)
constructor.
这篇关于在循环中运行时,随机数发生器总是选择相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!