问题描述
我只是想知道 C# 中的随机数生成器是如何工作的.我也很好奇如何编写一个程序来生成从 1 到 100 的随机 Whole INTEGER 数字.
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.
推荐答案
我只是想知道 C# 中的随机数生成器是如何工作的.
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.
我也很好奇如何编写一个程序来生成从 1 到 100 的随机整数.
I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.
您可以使用 Random.Next(int, int)代码>:
You can use Random.Next(int, int)
:
Random rng = new Random();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(rng.Next(1, 101));
}
请注意,上限是独有的 - 这就是我在这里使用 101 的原因.
Note that the upper bound is exclusive - which is why I've used 101 here.
您还应该了解与 Random
相关的一些陷阱" - 特别是,您应该不在每次想要生成随机数,否则如果您在短时间内生成大量随机数,您会看到很多重复.有关详细信息,请参阅我关于此主题的文章.
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# 的随机数生成器是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!