码迷,mamicode.com
首页 > Windows程序 > 详细

C#中的 new Random()

时间:2015-08-05 20:10:01      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:

在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)); //调用同一个 对象产生随机数。
            }

 运行结果:

技术分享

也可以实现随机的效果。

 

C#中的 new Random()

标签:

原文地址:http://www.cnblogs.com/huaan011/p/4705444.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!