掌握c#
中的随机整数生成 C#使用Random
>类提供了一种直接生成随机数,尤其是整数的方法。本指南演示了如何在定义的范围内生成随机整数。
>步骤1:初始化随机数生成器
>首先,创建一个Random
类的实例:
<code class="language-csharp">Random random = new Random();</code>
步骤2:利用Next()
方法
>
Next()
Random
类的方法生成随机整数。 要指定一个范围,请提供最小(包含)和最大(独家)值作为参数:
<code class="language-csharp">// Random integer between 1 and 12 (inclusive of 1, exclusive of 13) int month = random.Next(1, 13); // Random integer between 1 and 6 (inclusive of 1, exclusive of 7) int diceRoll = random.Next(1, 7); // Random integer between 0 and 51 (inclusive of 0, exclusive of 52) int cardIndex = random.Next(52);</code>
。 >
>最佳实践:重复使用随机实例> 对于真正的随机数字和唯一的数字,请重复使用相同的
实例。 快速连续创建多个实例可以导致类似的序列,因为种子通常默认为系统时钟。 始终使用单个实例可确保更好的随机性。以上是如何在C#中生成随机整数?的详细内容。更多信息请关注PHP中文网其他相关文章!