我正在尝试创建一个程序,只要按下它就会切换button1的位置。由于一些奇怪的原因,随机不是随机性很好。 Button1只是沿着倾斜-45度的同一对角线继续前进。
public void button1_Click(object sender, EventArgs e)
{
int tempX, tempY;
Random but1X = new Random();
tempX = but1X.Next(10, 500);
Random but1Y = new Random();
tempY=but1Y.Next(60,490);
button1.Location = new Point(tempX, tempY);
}
我听说原因是因为每当按钮1被按下时我都会不断创建一个新的随机实例,但是当我尝试将随机代码放入方法时,我仍然得到相同的结果。知道我怎么能让这个按钮实际上随机移动,而不是只是在幻灯片上下移动?
答案 0 :(得分:4)
尝试不为每个随机值实例化它:
public void button2_Click(object sender, EventArgs e)
{
int tempX, tempY;
Random rnd = new Random();
tempX = rnd.Next(10, 500);
tempY = rnd.Next(60,490);
button1.Location = new Point(tempX, tempY);
}
我用两个按钮对它进行了测试,它可以随机分配。
答案 1 :(得分:-1)
所有时间新的随机数.....这里打印标签“New_Random”
try
{
Random randomClass = new Random();
List<int> collection = new List<int>();
while (collection.Count <= 100)
{
var temp = randomClass.Next(1, 40);
if (!collection.Contains(temp))
{
collection.Add(temp);
int New_Reandom = Convert.ToInt32(temp);
}
}
}
catch
{
}