在循环中的随机数 [英] Random number in a loop
问题描述
有一个问题在一个循环中产生随机数。可以避开它通过使用Thread.sleep代码,但一个更优雅的解决方案了。
having an issue generating random numbers in a loop. Can get around it by using Thread.Sleep but after a more elegant solution.
for ...
Random r = new Random();
string += r.Next(4);
将结束与11111 ... 222 ...等。
Will end up with 11111... 222... etc.
建议?
推荐答案
将随机数发生器的声明跳出循环。
Move the declaration of the random number generator out of the loop.
的随机数生成从种子值开始。如果相同的种子被重复使用,则产生相同的一系列数字。产生不同序列的一个方法是使种子值随时间变化的,从而产生不同系列具有随机的每一个新的实例。默认情况下,Random类的参数的构造函数使用系统时钟产生的种子值,...
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, ...
由于被迫在循环中声明你有效地一遍又一遍呼唤具有相同值的构造 - 因此你得到了相同的号码
By having the declaration in the loop you are effectively calling the constructor with the same value over and over again - hence you are getting the same numbers out.
所以你的code应该变成:
So your code should become:
Random r = new Random();
for ...
string += r.Next(4);
这篇关于在循环中的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!