How do I generate a random int number?

前端 未结 30 2665
长发绾君心
长发绾君心 2020-11-21 11:02

How do I generate a random integer in C#?

30条回答
  •  梦谈多话
    2020-11-21 11:57

    Use one instance of Random repeatedly

    // Somewhat better code...
    Random rng = new Random();
    for (int i = 0; i < 100; i++)
    {
        Console.WriteLine(GenerateDigit(rng));
    }
    ...
    static int GenerateDigit(Random rng)
    {
        // Assume there'd be more logic here really
        return rng.Next(10);
    }
    

    This article takes a look at why randomness causes so many problems, and how to address them. http://csharpindepth.com/Articles/Chapter12/Random.aspx

提交回复
热议问题