创建随机数?(在控制台中) [英] create Random Numbers?(in Console)
问题描述
我怎样才能创建4位数的随机数?不使用结构循环和结构条件(例如Loop for,while,if,...)并且不使用Timer
此程序的结果如此程序:
4位数生成必须不同,例如,如果返回1111为假。但结果1234是真的。
Hi,How can I create 4-digit Random Numbers? without use Structural Loops and Structural condition (for example Loop for,while,if,...) and without use from Timer
result of this program like this program:
4-digit Produced Must different for example if return 1111 is false. but result 1234 is true.
static void Main(string[] args)
{
Random Item = new Random();
int Num1, Num2, Num3, Num4;
do
{
Num1 = Item.Next(0, 10);
Num2 = Item.Next(0, 10);
Num3 = Item.Next(0, 10);
Num4 = Item.Next(0, 10);
} while (Num1 == Num2 || Num1 == Num3 || Num1 == Num4 || Num2 == Num3 || Num2 == Num4 || Num3 == Num4);
Console.WriteLine("{0}{1}{2}{3}", Num1, Num2, Num3, Num4);
Console.ReadKey();
}
推荐答案
将数字0 - 9粘贴在一个列表中。随机拉出一个(并从列表中删除)。再做三次。
Stick the numbers 0 - 9 in a list. Pull one out at random (and remove from list). Do three more times.
不使用计时器只是胡言乱语。我建议使用System.DateTime.Now
,而不是计时器,用于随机数生成器,遵循Microsoft源代码(参见):如何创建随机数? [ ^ ]。
Microsoft建议
"Without use from Timer" is just gibberish. I advised to useSystem.DateTime.Now
, not timer, for random number generator, following Microsoft source code (see it): How Can I create Random Numbers?[^].
Microsoft recommends
new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
但我会避免使用
but I would avoid type cast by using
System.Random Item = new System.Random(System.DateTime.Now.Ticks.GetHashCode());
现在,你的问题没有解释。你的代码应该可以运行,但也许它远非最优。
请参阅解决方案2,以便更好地解释你能做得更好。
你的工作还有一个问题:不要在控制台中开发随机数。始终从任何UI和其他不相关的方面抽象出您的解决方案,使它们具有普遍性。你应该开发一个单独的功能。比如,它可以接受 Random
的实例和作为参数的位数,或者更通用。 Random
应该是一个参数,而不是在函数内创建的对象,所以这个对象可以在外面创建并可以重复使用。
Now, your "problem" is not explained. Your code should work, but perhaps it's far from optimal.
See Solution 2 for good explanation of what could you better do.
One more problem with your work: don't develop "random number in console". Always abstract out your solutions from any UI and other unrelated aspects, make them universal. You should develop a separate function. Say, it may accept an instance of Random
and number of digits as parameters, or be more universal. Random
should really be a parameter, not object created inside a function, so this object could be created outside and be reusable.
这篇关于创建随机数?(在控制台中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!