How do I generate a random int number?

前端 未结 30 2625
长发绾君心
长发绾君心 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.

    0 讨论(0)
  • 2020-11-21 11:45

    Beware that new Random() is seeded on current timestamp.

    If you want to generate just one number you can use:

    new Random().Next( int.MinValue, int.MaxValue )

    For more information, look at the Random class, though please note:

    However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers

    So do not use this code to generate a series of random number.

    0 讨论(0)
  • 2020-11-21 11:46

    Why not use int randomNumber = Random.Range(start_range, end_range) ?

    0 讨论(0)
  • 2020-11-21 11:47

    Try these simple steps to create random numbers:

    Create function:

    private int randomnumber(int min, int max)
    {
        Random rnum = new Random();
        return rnum.Next(min, max);
    }
    

    Use the above function in a location where you want to use random numbers. Suppose you want to use it in a text box.

    textBox1.Text = randomnumber(0, 999).ToString();
    

    0 is min and 999 is max. You can change the values to whatever you want.

    0 讨论(0)
  • 2020-11-21 11:48

    The numbers generated by the inbuilt Random class (System.Random) generates pseudo random numbers.

    If you want true random numbers, the closest we can get is "secure Pseudo Random Generator" which can be generated by using the Cryptographic classes in C# such as RNGCryptoServiceProvider.

    Even so, if you still need true random numbers you will need to use an external source such as devices accounting for radioactive decay as a seed for an random number generator. Since, by definition, any number generated by purely algorithmic means cannot be truly random.

    0 讨论(0)
  • 2020-11-21 11:49

    You can try with random seed value using below:

    var rnd = new Random(11111111); //note: seed value is 11111111
    
    string randomDigits = rnd.Next();
    
    var requestNumber = $"SD-{randomDigits}";
    
    0 讨论(0)
提交回复
热议问题