如何在C#中随机化种子 [英] How to randomize seed in C#
问题描述
我需要在C#中生成随机整数.我正在使用时钟时间设置seed.但是,由于rnd.Next()函数可能需要不到一毫秒的时间,因此如果必须生成一个int列表,则此方法将无效.
I need to generate random int in C#. I am using clock time to set the seend. However, as the rnd.Next() function may take less than a millisecond, this does not work if one has to generate a list of ints.
for( int i=0; i<5; i++) {
int max_val = 10; // max value
var rnd = new Random(DateTime.Now.Millisecond);
int randind = rnd.Next(0, max_val);
Console.WriteLine(randind);
}
输出:
1个
5
5
5
5
Output:
1
5
5
5
5
如何在不增加丑陋睡眠的情况下以干净的方式随机分配种子?
How can one randomise the seed in a clean way without adding an ugly sleep?
推荐答案
在循环外部创建您的Random
对象,并且不提供种子参数-将会为您选择一个.通过将其移出循环,rnd.Next()仍然会为您提供随机序列.
Create your Random
object outside the loop and don't provide the seed parameter -- one will be picked for you. By taking it out of the loop, rnd.Next() will give you a random sequence anyway.
var rnd = new Random();
for( int i=0; i<5; i++) {
int max_val = 10; // max value
int randind = rnd.Next(0, max_val);
Console.WriteLine(randind);
}
这篇关于如何在C#中随机化种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!