如何在C#中生成随机整数?
当前回答
重复使用Random的一个实例
// Somewhat better code...
Random rng = new Random();
for (int i = 0; i < 100; i++)
{
Console.WriteLine(GenerateDigit(rng));
}
...
static int GenerateDigit(Random rng)
{
// Assume there'd be more logic here really
return rng.Next(10);
}
本文将探讨随机性为何会导致如此多的问题,以及如何解决这些问题。http://csharpindepth.com/Articles/Chapter12/Random.aspx
其他回答
虽然这还可以:
Random random = new Random();
int randomNumber = random.Next()
大多数情况下,您需要控制限制(最小和最大数量)。因此,您需要指定随机数的开始和结束位置。
Next()方法接受两个参数,min和max。
所以,如果我希望我的随机数介于5和15之间,我就这么做
int randomNumber = random.Next(5, 16)
如果您希望CSRNG生成最小值和最大值之间的随机数,这是适合您的。它将使用安全的随机种子初始化随机类。
class SecureRandom : Random
{
public static byte[] GetBytes(ulong length)
{
RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider();
byte[] bytes = new byte[length];
RNG.GetBytes(bytes);
RNG.Dispose();
return bytes;
}
public SecureRandom() : base(BitConverter.ToInt32(GetBytes(4), 0))
{
}
public int GetRandomInt(int min, int max)
{
int treashold = max - min;
if(treashold != Math.Abs(treashold))
{
throw new ArithmeticException("The minimum value can't exceed the maximum value!");
}
if (treashold == 0)
{
throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
}
return min + (Next() % treashold);
}
public static int GetRandomIntStatic(int min, int max)
{
int treashold = max - min;
if (treashold != Math.Abs(treashold))
{
throw new ArithmeticException("The minimum value can't exceed the maximum value!");
}
if(treashold == 0)
{
throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
}
return min + (BitConverter.ToInt32(GetBytes(4), 0) % treashold);
}
}
根据定义,由计算机通过确定性过程计算的数字不能是随机的。
如果你想要一个真正的随机数,随机性来自大气噪声或放射性衰变。
例如,您可以尝试RANDOM.ORG(它会降低性能)
创建随机对象
Random rand = new Random();
并使用它
int randomNumber = rand.Next(min, max);
你不必每次需要一个随机数时都初始化新的Random(),先初始化一个Random,然后在循环中使用它,或者其他
有许多实用程序函数或服务以与System.Random相同的方式更好地缓存,因此它适合于通用实现:
static public class CachedService<T> where T : new() {
static public T Get { get; } = new T();
}
用于随机(或类似):
CachedService<System.Random>.Get.Next(999);
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 如何在Ruby中生成a和b之间的随机数?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?