简体   繁体   English

如何生成一组由C#中一定位数组成的数字?

[英]How to generate a set of numbers consisting of a certain number of digits in C#?

I have to generate a set of numbers consisting of 5 digits, as shown below.我必须生成一组由 5 位数字组成的数字,如下所示。 I tried to search some info about this but found nothing.我试图搜索有关此的一些信息,但一无所获。

int playerId;

System.Random rand = new System.random();
for (int i = 0; i <= 5; i++)
{
     playerId = random.Next();
}
Console.Write($"Generating player ID: {playerId}");

// output example: Generating player ID:  1158453178

As a result, i got a set of numbers consisting of 10 digits.结果,我得到了一组由 10 位数字组成的数字。 How can i solve this problem?我怎么解决这个问题?

What you're doing in your code is generating five different random numbers of 10 digits ( random.Next() generates integers less than the integer maximum value, 2147483647) and printing the last one.您在代码中所做的是生成五个不同的 10 位随机数( random.Next()生成小于 integer 最大值 2147483647 的整数)并打印最后一个。 If you want to generate a 5 digit random number, you can just use random.Next(100000).ToString("D5") , which will generate a random positive integer under 100,000, and then fill out the front with zeroes if needed.如果你想生成一个5位的随机数,你可以直接使用random.Next(100000).ToString("D5") ,它会生成一个100,000以下的随机正数integer,然后根据需要用零填充前面。

you should put Console.Write($"Generating player ID: {playerId}");你应该把Console.Write($"Generating player ID: {playerId}"); inside the for block, something like this:在 for 块内,是这样的:

int playerId;
System.Random rand = new System.random();
for (int i = 0; i < 5; i++)
 {
  playerId = random.Next();
  Console.Write($"Generating player ID: {playerId}");
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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