Random barely randomming

2019-07-29 23:08发布

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

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?

标签: c# random
2条回答
小情绪 Triste *
2楼-- · 2019-07-29 23:37

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.

查看更多
Root(大扎)
3楼-- · 2019-07-29 23:49

all Time new Random Number..... here 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
{
}
查看更多
登录 后发表回答