随机 勉强随机 [英] Random barely randomming

查看:24
本文介绍了随机 勉强随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,当按钮 1 被按下时切换它的位置.出于某种奇怪的原因,随机不是很好地随机化.Button1 只是继续沿着倾斜 -45 度的同一条对角线移动.

I'm trying to make a program that switches the location of button1 whenever it gets pressed. For some odd reason, random isn't randomming so well. Button1 just keeps going along the same diagonal line that's slanted at -45 degrees.

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 时我都会创建一个新的 random 实例,但是当我尝试将随机代码放入方法中时,我仍然得到相同的结果.知道如何让这个按钮真正随机移动,而不是在幻灯片上上下移动吗?

I've heard that the reason for this is because I keep making a new instance of random whenever button1 gets pressed but when I've tried putting the random code in a method, I still get the same results. Any idea how I can get this button to actually move randomly, rather than just going up and down the slide?

推荐答案

尝试不为您想要的每个随机值实例化它:

Try without instantiating it for every random value you want:

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);
}

我用两个按钮对此进行了测试,并且在随机分布时效果很好.

I tested this with two buttons and it works well with random distribution.

这篇关于随机 勉强随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆