我在使用C#生成随机数时遇到问题。如果我直接RUN此表单应用程序,则所有的随机数生成都是相同的。
如果我通过按F10一行一行地DEBUG,则它将生成不同的随机数。为什么会这样呢?如何生成不同的随机数?
Greyhound.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ADayAtTheRaces
{
class Greyhound
{
int location=0;
Random randomize = new Random();
public int run()
{
location = randomize.Next(0, 100);
return location;
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ADayAtTheRaces
{
public partial class Form1 : Form
{
Greyhound[] greyHound = new Greyhound[4];
ProgressBar[] progressBar = new ProgressBar[4];
public Form1()
{
InitializeComponent();
for (int i = 0; i < 4; i++)
{
greyHound[i] = new Greyhound();
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= 3; i++)
{
progressBar[i].Value = greyHound[i].run();
}
}
}
}
不要每次都实例化一个新的Random
对象,而是将其用作static
成员:
您正在同时创建x数量的新随机数。
您的答案在这里:Random Constructor
戴维德说得很对。实际上,这就是修复代码的方式。
尝试使随机化为静态。我猜问题出在种子是时间依赖的事实。
之所以获得相同的随机数,是因为您正在为每个实例创建一个Random对象。随机生成器是从时钟开始播种的,因此当您创建时间太近的随机对象时,它们最终都将具有相同的种子,并产生相同的随机数。
每次实例化GreyHound的实例时,都实例化System.Random
的实例。 System.Random
的默认构造函数使用System.Environment.TickCount 作为生成随机数的种子。 System.Environment.TickCount
的分辨率为毫秒,因此您创建实例的速度要快得多。也许使System.Random实例正在使用static
...将可以解决问题。
之所以发生这种情况,是因为调试花费的时间很少,而且可以随机更改。滥用它,对我有帮助