Correct method of a “static” Random.Next in C#?

前端 未结 11 2230
执念已碎
执念已碎 2020-12-10 10:51

Why do i need to create an instance of Random class, if i want to create a random number between 1 and 100 ....like

Random rand = new Random();
rand.Next(1,1         


        
11条回答
  •  情话喂你
    2020-12-10 11:10

    Creating a new instance of Random then calling it immediately multiple times, e.g.:

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

    Will give you a distribution that is weighted towards the lower end of the range.

    Doing it this way:

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

    Will give you a better distribution.

提交回复
热议问题