C# 生成 4-8 位随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17160122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:43:37  来源:igfitidea点击:

Generating a 4–8 digit random number

c#random

提问by vini

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#?

这也会生成 2 位和 3 位数字。如何在 C# 中生成 4-8 位随机数?

采纳答案by Ry-

Start at the smallest 4-digit number, end at the smallest 9-digit number (exclusive):

从最小的 4 位数字开始,到最小的 9 位数字(不包括)结束:

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

回答by AgentFire

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));
}

回答by Pinch

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

涵盖您所有的基数(1000 以下的数字,例如 0002)

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

回答by Vladimir G. Nosov

new Random(Guid.NewGuid().GetHashCode()).Next(0, 9999).ToString("D4")

new Random(Guid.NewGuid().GetHashCode()).Next(0, 9999).ToString("D4")