如何C#的随机数生成器的工作? [英] How does C#'s random number generator work?

查看:248
本文介绍了如何C#的随机数生成器的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道如何在C#中的作品随机数发生器。我也很好奇我怎么能作出这样生成一个随机程序的所有整数从1-100的数字。


解决方案

我只是想知道如何随机数生成器在C#中的作品。




这是特定于实现的,但对于伪随机数生成器应该给你一些想法维基百科条目。




我也好奇,我怎么能作出这样的1-100生成随机全整数的程序。


< /块引用>

您可以使用 随机。接下来(INT,INT)

 随机RNG =新的随机() ; 
的for(int i = 0;我小于10;我++)
{
Console.WriteLine(rng.Next(1,101));
}



需要注意的是上界的独家的 - 这就是为什么我用101这里。



您也应该了解一些与随机相关的陷阱的 - 尤其是你应该的的创建一个新的实例每次你想生成一个随机数,否则如果你生成大量随机数在短时间内,你会看到很多重复。请参见我获得更多细节,这个话题文章。


I was just wondering how the random number generator in C# works. I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

解决方案

I was just wondering how the random number generator in C# works.

That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.

I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

You can use Random.Next(int, int):

Random rng = new Random();
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(rng.Next(1, 101));
}

Note that the upper bound is exclusive - which is why I've used 101 here.

You should also be aware of some of the "gotchas" associated with Random - in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.

这篇关于如何C#的随机数生成器的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆