加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:02:44 所属栏目:百科 来源:网络整理
导读:参见英文答案 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读