且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在循环中的随机数

更新时间:2023-11-09 20:15:28

将随机数发生器的声明跳出循环。

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);