C# 随机

C# 随机,c#,random,C#,Random,我正在尝试制作一个程序,每当按下按钮1时,它就会切换按钮1的位置。出于某种奇怪的原因,random并不是很好。按钮1只是一直沿着同一条斜线移动,斜角为-45度 public void button1_Click(object sender, EventArgs e) { int tempX, tempY; Random but1X = new Random(); tempX = but1X.Next(10, 500);

我正在尝试制作一个程序,每当按下按钮1时,它就会切换按钮1的位置。出于某种奇怪的原因,random并不是很好。按钮1只是一直沿着同一条斜线移动,斜角为-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);
    }
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
{
}

我听说这样做的原因是,每当按下按钮1时,我总是创建一个新的随机实例,但当我尝试将随机代码放入方法中时,我仍然得到相同的结果。你知道我怎样才能让这个按钮真正随机移动,而不仅仅是在幻灯片上下移动吗?

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

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

我用两个按钮对此进行了测试,它可以很好地用于随机分布。

所有时间新随机数。。。。。此处打印标签“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
{
}
试试看
{
Random randomClass=新的Random();
列表集合=新列表();

while(collection.Count)您希望使用相同的Random()种子;在每次调用Next()之前不要创建新的Random()对象。首先,Random只生成伪随机序列。其次,“种子”序列的长度是基于当前时间的,所以如果你在同一毫秒内创建两个随机对象——这在现代硬件上没有问题——它们将生成相同的序列。只创建一个随机对象(每个线程),或者,如果您需要真正的随机性,请使用一个加密强度随机性API,该API不使用当前时间作为种子。欢迎使用。祝您好运!空的general
catch
是一种糟糕的做法。问题并没有说明如何获得“唯一随机性”你正在尝试的数字。你的代码将永远循环,在1和40之间没有100个唯一的数字。