【发布时间】:2018-08-13 20:21:34
【问题描述】:
我有一个简单的程序,它使用 Random 和一个 for 循环来生成两个六位数。循环每次生成两个数字,大多数时候这两个数字都是六位数。但有时,其中一个数字小于 6 位(4 到 5 位)。它在所有情况下都不会生成错误消息。这是怎么回事?我已经发布了所有代码,尽管其中一些代码在我找出随机问题之前没有使用/测试过。
六位数字以空字符串开头。随机生成一个整数,整数转换为字符串,然后 += 转换为六位数字字符串,当方法完成时将其转换为整数。
该程序的其余部分未实现,将涉及提取每个数字中的第 2、第 4 和第 6 位数字并将它们加在一起。麻烦的是随机问题。
static void Main(string[] args)
{
Numbers theNumbers = new Numbers();
Console.WriteLine(string.Join(",", theNumbers.Ints[0]));
Console.WriteLine(string.Join(",", theNumbers.Ints[1]));
}
数字类
class Numbers
{
public int[] Ints { get; set; }
public Numbers()
{
Ints = new int[5];
CreateTheFirstTwoNumbers(new RandomNummberGenerator());
}
public int[] CreateTheFirstTwoNumbers(RandomNummberGenerator RNG)
{
for (int arrayIndex = 0; arrayIndex < 2; arrayIndex++)
{
Ints[arrayIndex] = RNG.CreateRandomNumber();
}
return Ints;
}
随机数生成器类
class RandomNummberGenerator
{
public Random Generator { get; set; }
public RandomNummberGenerator()
{
Generator = new Random();
}
public int CreateRandomNumber()
{
string number = "";
for (int numberIndex = 0; numberIndex < 6; numberIndex++)
{
number += Generator.Next(0, 10).ToString();
}
return int.Parse(number);
}
}
【问题讨论】:
-
仅包含与您的问题相关的代码,这些
//unusedcmets 向我表明没有使用代码,因此请从您的问题中删除它 -
欢迎堆栈溢出。为了最大限度地提高您获得帮助的机会,请尝试提供minimal, complete, verifiable example您遇到的问题
-
@aGuy 您可以通过
Generator.Next(100000, 1000000)为您的生成器播种,使其仅产生 6 位数字,是否有理由不能只获得随机的 6 位数字而不是获得随机数0 - 9 并将它们附加在一起?