How does C##39;s random number generator work?(C# 的随机数生成器是如何工作的?)
问题描述
我只是想知道 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# 的随机数生成器是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 的随机数生成器是如何工作的?


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04