循环中的随机数 [英] Random number in a loop

查看:32
本文介绍了循环中的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在循环中生成随机数时遇到问题.可以通过使用 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 实例产生不同的序列.默认情况下,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.

所以你的代码应该变成:

So your code should become:

Random r = new Random();
for ...
    string += r.Next(4);

这篇关于循环中的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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