C#随机生成 [英] C# Random generation

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

问题描述

我刚刚在线上传递了这篇文章:

I have just passed this article online: C# Corner and C# Corner and his article (a software developer with over 13 years of experience) recommended using System.Random as follows:

private int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max); 
}

不是每次都会给他相同的号码吗?

Isn't that would give him the same number every time ??


所以我的问题将变成:Random如何选择其种子?一个恒定的或当前的时间值?


So my question will become: How does Random choose its seed? a constant or current time value?

谢谢

推荐答案

当经常在较短的时间间隔之间调用该方法时,它将给出相同的结果.这是因为Random的种子是使用当前时间值初始化的. 这也是为什么许多人会遇到随机根本不是随机的问题的原因.

It will give the same result when the method will be called often between short time intervals. This is because the Randoms seed is initialized with the current time value. This is also the reason why many people have problem of kind that random is not random at all.

顺便说一句,它不是Math.Random,而是 System.Random

BTW it is not Math.Random but System.Random

在您进行编辑之后,以下是一些有关如何初始化随机数的信息.该信息来自上面的链接.

Following your edit, here is some information on how random is initialized. The information comes from the link above.

随机数生成开始 从种子值开始.如果是相同的种子 重复使用,相同系列 数字已生成.一种方法 产生不同的顺序是为了 种子值与时间有关,因此 各自产生不同的系列 随机的新实例.默认情况下, 的无参数构造函数 随机类使用系统时钟 产生其种子价值,而其 参数化的构造函数可以采用 基于int32值的数量 在当前时间滴答作响.然而, 因为时钟有限 分辨率,使用无参数 构造函数创建不同的Random 紧密连续的对象创建 产生的随机数发生器 相同的随机数序列.

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.

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

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