Random获得的随机数怎么样减少重复率

C#中的Random在获得随机数的时,如果你想要随机循环取得100个随机数则使用如下代码会出现大量的重复数字。代码如下:

using System;

namespace ConsoleApplication1

{   

  class Program  

     {       

     static void Main(string[] args)     

      {           

            for (int i = 0; i < 100; i++)     

             {

               Random r = new Random();      

                 double n = r.Next(100) / 100;     

               n = getr(n, r);           

           string str1 = String.Format("{0:F}", n);     

                Console.WriteLine(str1+"%");       

         }           

              Console.Read();      

         }     

        static double getr(double temp, Random r)

        {           

              while (true)

             {                

                 if (temp < 90)

                 {   temp = r.NextDouble() * 100;  }              

                else  

                 {   return temp;   }       

           }      

        }

     }

}

效果如图所示:

这是因为Random使用与时间相关的默认种子,也就是说Random在生成随机数的时候,是在一定的时间内生成的,如此由于计算机的处理速度非常的快,因此在某段时间内生成的随机数,或许会出现相同的情况。这里该怎么解决呢,首先看以下代码:

using System;

using System.Threading;

namespace ConsoleApplication1

{   

  class Program  

     {      

     static void Main(string[] args)     

      {          

            for (int i = 0; i < 100; i++)     

             {

             Thread.Sleep(1000);

               Random r = new Random();      

                 double n = r.Next(100) / 100;     

               n = getr(n, r);           

           string str1 = String.Format("{0:F}", n);     

                Console.WriteLine(str1+"%");      

         }           

              Console.Read();      

         }     

        static double getr(double temp, Random r)

        {           

              while (true)

             {                

                 if (temp < 90)

                 {   temp = r.NextDouble() * 100;  }              

                else  

                 {   return temp;   }       

           }      

        }

     }

}

这里我们添加了Thread.Sleep(1000);这个函数,作用就是让该线程挂起一段时间,如此一来就可以跳出Random生成随机数的时间。这样,我们再生成随机数的时候就可以减少重复的数据。

效果如图所示:

 当然解决办法不止这一个,也可以将Random放到for循环的外面,对于原因这里要待续了。。。

有谁知道的也可以赐教一下。

原文地址:https://www.cnblogs.com/dolphin-gjh/p/3555052.html