为什么我的随机数发生器播种两个阵列使用相同的数字呢?我的、随机数、阵列、发生器

2023-09-04 00:57:45 作者:一点点喜欢

我使用的方法来创建两个新的 INT 阵列随机数, 但两个数组包含完全相同的编号。为什么会出现这种情况?

 静态无效的主要(字串[] args)
    {
        INT [] Foo1 =美孚(1000);
        INT [] foo2的=美孚(1000);
    }
    静态INT []美孚(INT长度)
    {
        INT []数组=新INT [长度];
        随机R =新的随机();
        的for(int i = 0; I<长度;我++)
        {
            阵列[I] = r.Next(1,101);
        }
        //Thread.Sleep(6);
        返回数组;
    }
 

解决方案

你不播种随机但你可能用它足够近调用之间,默认的种子是在两种情况下是相同的:

  

默认种子值源自   系统时钟和具有有限   解析度。其结果是,不同的   这在形成的随机对象   通过调用关闭继承   默认的构造函数都会有   相同的默认种子值和,   因此,会产生相同的集   的随机数。这个问题可以   通过使用单一随机避免   反对生成所有的随机数。   您也可以解决它通过   修改返回的种子值   系统时钟,然后明确   提供这种新的种子值的   随机(Int32)已构造。欲了解更多   信息,请参阅随机(Int32)已   构造函数。

I'm using a method to create two new int arrays with random numbers, but the two array contains exactly the same numbers. Why is this happening?

    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;
    }
excel 用rand 写的随机数 怎么返回数值 就是一次随机以后就不变了

解决方案

You're not seeding Random but you're likely using it close enough between calls that the default seed is the same in both cases :

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.

 
精彩推荐