C#中的 new Random()


在C#中,產生隨機數常用大方法是 new Random().Next(1,10)等方法。

但是仔細發現會有個問題:

看代碼:

for (int i = 0; i < 100;i++ )
            {
                Console.WriteLine(new Random().Next(1, 100));
            }
           
          Console.ReadKey(); 

 

 運行結果:

發現隨機的數基本都是一樣的。就有問題了,每次隨機的都是一樣的,就不是隨機數了。

仔細查看 Random的構造函數

public Random() : this(Environment.TickCount)
        {
        }
        /// <summary>Initializes a new instance of the <see cref="T:System.Random" /> class, using the specified seed value.</summary>
        /// <param name="Seed">A number used to calculate a starting value for the pseudo-random number sequence. If a negative number is specified, the absolute value of the number is used. </param>
        [__DynamicallyInvokable]
public Random(int Seed)
        {
            int num = (Seed == -2147483648) ? 2147483647 : Math.Abs(Seed);
            int num2 = 161803398 - num;
            this.SeedArray[55] = num2;
            int num3 = 1;
            for (int i = 1; i < 55; i++)
            {
                int num4 = 21 * i % 55;
                this.SeedArray[num4] = num3;
                num3 = num2 - num3;
                if (num3 < 0)
                {
                    num3 += 2147483647;
                }
                num2 = this.SeedArray[num4];
            }
            for (int j = 1; j < 5; j++)
            {
                for (int k = 1; k < 56; k++)
                {
                    this.SeedArray[k] -= this.SeedArray[1 + (k + 30) % 55];
                    if (this.SeedArray[k] < 0)
                    {
                        this.SeedArray[k] += 2147483647;
                    }
                }
            }
            this.inext = 0;
            this.inextp = 21;
            Seed = 1;
        }

 

 

無參的構造函數其實調用的是 有參的構造函數,傳遞的 默認值: Environment.TickCount

 System.Environment.TickCount 獲取開機時間函數。

也就是說每次傳遞進去的都是一樣的值。

如果我們,改下代碼,給 new Random()傳參.

 for (int i = 0; i < 10;i++ )
            {
                Console.WriteLine(new Random(Guid.NewGuid().GetHashCode()).Next(1, 10));
            }

 

 這次的運行結果:

明顯的不一樣了。就是隨機的效果了。

 

還有一種方式也可以實現隨機的效果:

     Random rnd = new Random(); //在外面生成對象
            for (int i = 0; i < 10;i++ )
            {
                Console.WriteLine(rnd.Next(1, 10)); //調用同一個 對象產生隨機數。
            }

 運行結果:

也可以實現隨機的效果。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM