Unique 4 digit random number in C#

前端 未结 11 2014
故里飘歌
故里飘歌 2021-01-01 13:27

I want to generate an unique 4 digit random number. This is the below code what I have tried:

Code for generating random number

//Ge         


        
相关标签:
11条回答
  • 2021-01-01 13:51
    int NoDigits = 4;
    Random rnd = new Random();
    textBox2.Text = rnd.Next((int)Math.Pow(10, (NoDigits - 1)), (int)Math.Pow(10, NoDigits) -1).ToString();
    
    0 讨论(0)
  • //Generate RandomNo
    public int GenerateRandomNo()
    {
        int _min = 1000;
        int _max = 9999;
        Random _rdm = new Random();
        return _rdm.Next(_min, _max);
    }
    

    you need a 4 digit code, start with 1000

    0 讨论(0)
  • 2021-01-01 13:59

    Use this code instead:

    private Random _random = new Random();
    
    public string GenerateRandomNo()
    {
        return _random.Next(0, 9999).ToString("D4");
    }
    
    0 讨论(0)
  • 2021-01-01 14:01

    0 is the same as 0000.

    241 is the same as 0241.

    You could format the integer to a string with a leading zero.

    0 讨论(0)
  • 2021-01-01 14:04

    Just one line code

    int num = new Random().Next(1000, 9999);
    
    0 讨论(0)
提交回复
热议问题