微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

参见英文答案 > 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 @R_870_4045@ion,see the Random(Int32) constructor.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐