简体   繁体   中英

Generating a 4–8 digit random number

Random random = new Random();
int password = random.Next(10000);

This generates 2-digit and 3-digit numbers also. How do I generate a 4–8 digit random number in C#?

从最小的4位数字开始,以最小的9位数字结尾(独家):

int password = random.Next(1000, 100000000);

You could also make a method:

public static int GetRandom(int minDigits, int maxDigits)
{
    if (minDigits < 1 || minDigits > maxDigits)
        throw new ArgumentOutOfRangeException();

    return (int)random.Next(Math.Pow(10, minDigits - 1), Math.Pow(10, maxDigits - 1));
}

To cover all your bases (numbers under 1000 such as 0002)

Random RandomPIN = new Random();
var RandomPINResult = RandomPIN.Next(0, 9999).ToString();
RandomPINResult = RandomPINResult.PadLeft(4, '0');

new Random(Guid.NewGuid()。GetHashCode())。Next(0,9999).ToString(“D4”)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM