gpt4 book ai didi

C# 绘图,奇怪的行为

转载 作者:行者123 更新时间:2023-11-30 19:08:02 29 4
gpt4 key购买 nike

以下代码相当简单 - 它用随机选择的像素填充设计表面 - 没什么特别的(暂时忽略第二种方法中的 XXXXXXX)。

private void PaintBackground()
{
Random rnd = new Random();

Bitmap b = new Bitmap(this.Width, this.Height);
for (int vertical = 0; vertical < this.Height; vertical++)
{
for (int horizontal = 0; horizontal < this.Width; horizontal++)
{
Color randomColour = GetRandomColor(rnd);
b.SetPixel(horizontal, vertical, randomColour);
}
}

Graphics g = this.CreateGraphics();
g.DrawImage(b, new Point(0, 0));
}

public Color GetRandomColor(Random rnd)
{
XXXXXXXXXXXXXXXX

byte r = Convert.ToByte(rnd.Next(0, 255));
byte g = Convert.ToByte(rnd.Next(0, 255));
byte b = Convert.ToByte(rnd.Next(0, 255));

return Color.FromArgb(255, r, g, b);
}

我的问题是...

如果将 XXXXXXXXX 替换为“Random rnd = new Random();”测试图案完全变成相同颜色的水平条,因此不是随机的。

谁来给我解释一下这是为什么?

据我所知,第二次尝试的唯一区别是 GetRandomColour 方法创建并使用了 Random 类的一个新实例,但我看不出这是如何生成水平条的。

最佳答案

来自 MSDN :

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. The following example illustrates that two Random objects that are instantiated in close succession generate an identical series of random numbers.

因此,给定相同的种子,Random 实例将产生相同的数字序列。在您的示例中,由于系统时钟的有限分辨率,随机实例是使用与种子相同的滴答计数创建的,从而产生相同的序列。

GetRandomColor() 的连续调用在系统时钟的一个时间片内执行。要对此进行测试,请尝试使用 Thread.Sleep(1) 减慢该方法的速度。您应该会看到生成了不同的颜色。

关于C# 绘图,奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2093500/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com