c# – 为什么我的随机数生成器为两个数组播种相同的数字?

c# – 为什么我的随机数生成器为两个数组播种相同的数字?,第1张

概述参见英文答案 > Random number generator only generating one random number                                    9个 我正在使用一种方法来创建两个带有随机数的新int数组, 但是这两个数组包含完全相同的数字.为什么会这样? static void Main(string[] args) { 参见英文答案 > Random number generator only generating one random number                                    9个
我正在使用一种方法来创建两个带有随机数的新int数组,
但是这两个数组包含完全相同的数字.为什么会这样?

static voID Main(string[] args)    {        int[] Foo1= Foo(1000);        int[] Foo2= Foo(1000);    }    static int[] Foo(int length)    {        int[] Array = new int[length];        Random r = new Random();        for (int i = 0; i < length; i++)        {                      Array[i]=r.Next(1,101);           }        //Thread.Sleep(6);        return Array;    }
解决方法 你不是 seeding Random但是你可能在调用之间使用它足够接近默认种子在两种情况下是相同的:

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.

总结

以上是内存溢出为你收集整理的c# – 为什么我的随机数生成器为两个数组播种相同的数字?全部内容,希望文章能够帮你解决c# – 为什么我的随机数生成器为两个数组播种相同的数字?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1225781.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存