随机,几乎是随机
本文关键字:随机 | 更新日期: 2023-09-27 18:03:05
我正在尝试制作一个程序,每当按下按钮时切换按钮1的位置。出于一些奇怪的原因,随机并不是很好地随机化。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);
}
我听说这样做的原因是因为每当button1被按下时,我一直在创建一个新的随机实例,但是当我尝试将随机代码放在方法中时,我仍然得到相同的结果。知道怎么让这个按钮随机移动吗,而不是在幻灯片上上下移动?
尝试不实例化每个你想要的随机值:
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);
}
我用两个按钮测试了这个,它在随机分布下工作得很好。
all Time new Random Number.....Print in label "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
{
}