How do I generate a random int number?

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

How do I generate a random integer in C#?

30条回答
  •  温柔的废话
    2020-11-21 11:45

    The Random class is used to create random numbers. (Pseudo-random that is of course.).

    Example:

    Random rnd = new Random();
    int month  = rnd.Next(1, 13);  // creates a number between 1 and 12
    int dice   = rnd.Next(1, 7);   // creates a number between 1 and 6
    int card   = rnd.Next(52);     // creates a number between 0 and 51
    

    If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

提交回复
热议问题