如何生成随机整数? [英] How do I generate a random int number?

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

问题描述

如何在 C# 中生成随机整数?

How do I generate a random integer in C#?

推荐答案

Random 用于创建随机数.(当然是伪随机.)

The Random class is used to create random numbers. (Pseudo-random that is of course.).

示例:

Random rnd = new Random();
int month  = rnd.Next(1, 13);  // creates a number between 1 and 12
int dice   = rnd.Next(1, 7);   // creates a number between 1 and 6
int card   = rnd.Next(52);     // creates a number between 0 and 51

如果您要创建多个随机数,您应该保留 Random 实例并重复使用它.如果您创建的新实例时间太近,它们将产生与随机生成器从系统时钟中生成种子相同的一系列随机数.

If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

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

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