- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
您好,我在使用 C# 生成随机数时遇到了一些问题现在我有了这个功能。
public Color getRandomColor()
{
Color1 = new Random().Next(new Random().Next(0, 100), new Random().Next(200, 255));
Color2 = new Random().Next(new Random().Next(0, 100), new Random().Next(200, 255));
Color3 = new Random().Next(new Random().Next(0, 100), new Random().Next(200, 255));
Color color = Color.FromArgb(Color1, Color2, Color3);
Console.WriteLine("R: " + Color1 + " G: " + Color2 + " B: " + Color3 + " = " + color.Name);
return color;
}
现在您可能会注意到那里有很多 new Random(),那是因为我想排除它可能是同一实例错误的可能性。
我现在运行此函数 8 次,几次。现在这是输出。
R: 65 G: 65 B: 65 = ff414141
R: 242 G: 242 B: 242 = fff2f2f2
R: 205 G: 205 B: 205 = ffcdcdcd
R: 40 G: 40 B: 40 = ff282828
R: 249 G: 249 B: 249 = fff9f9f9
R: 249 G: 249 B: 249 = fff9f9f9
R: 94 G: 94 B: 94 = ff5e5e5e
R: 186 G: 186 B: 186 = ffbababa
R: 142 G: 142 B: 142 = ff8e8e8e
R: 190 G: 190 B: 190 = ffbebebe
R: 19 G: 19 B: 19 = ff131313
R: 119 G: 119 B: 119 = ff777777
R: 119 G: 119 B: 119 = ff777777
R: 75 G: 75 B: 75 = ff4b4b4b
R: 169 G: 169 B: 169 = ffa9a9a9
R: 127 G: 127 B: 127 = ff7f7f7f
R: 73 G: 73 B: 73 = ff494949
R: 27 G: 27 B: 27 = ff1b1b1b
R: 125 G: 125 B: 125 = ff7d7d7d
R: 212 G: 212 B: 212 = ffd4d4d4
R: 174 G: 174 B: 174 = ffaeaeae
R: 0 G: 0 B: 0 = ff000000
R: 0 G: 0 B: 0 = ff000000
R: 220 G: 220 B: 220 = ffdcdcdc
如您所见,这又不是那么随机了,但为什么会发生这种情况?我该如何应对?
最佳答案
您正在为每个需要的单个值创建一个新的 Random
。
尝试创建一个独特的 Random
对象并多次调用 .Next()
函数。
public Color getRandomColor()
{
Random rand = new Random();
Color1 = rand.Next(rand.Next(0, 100), rand.Next(200, 255));
Color2 = rand.Next(rand.Next(0, 100), rand.Next(200, 255));
Color3 = rand.Next(rand.Next(0, 100), rand.Next(200, 255));
Color color = Color.FromArgb(Color1, Color2, Color3);
Console.WriteLine("R: " + Color1 + " G: " + Color2 + " B: " + Color3 + " = " + color.Name);
return color;
}
取自MSDN documentation on Random object :
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# - 偶遇不那么随机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2727538/
我是一名优秀的程序员,十分优秀!