zoukankan      html  css  js  c++  java
  • 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)); //调用同一个 对象产生随机数。
                }

     运行结果:

    也可以实现随机的效果。

  • 相关阅读:
    C#针对js escape解码
    .NET XML序列化与反序列化
    数据库文档生成工具(1)
    小欣外贸助手-国际站排名查询工具限量封测了
    七夕小福利
    利用正则表达式获取博客园随笔(四)
    利用正则表达式获取博客园随笔
    利用正则表达式获取博客园随笔(三)
    利用正则表达式获取博客园随笔(二)
    利用正则表达式获取博客园随笔(一)
  • 原文地址:https://www.cnblogs.com/huaan011/p/4705444.html
Copyright © 2011-2022 走看看