C#-正在显示重复的随机数

时间:2018-10-25 21:48:26

标签: c# winforms random

我已经编写了这种非常粗糙的方式来生成随机数并在Windows窗体内的labelText中显示。发生的是,第二个标签文本显示的内容与第一个标签文本完全相同。希望您能就如何纠正此问题提供反馈,以便每个标签文本显示唯一的随机数。

    private void btnGenerateNumbers_Click(object sender, EventArgs e)
    {
        List<string> numberStringT = new List<string>();


        for (int i = 0; i < 2; i++)
        {
            string result = "";
            Random rnd = new Random();
            int one = rnd.Next(1, 49);
            int two = rnd.Next(1, 49);
            int three = rnd.Next(1, 49);
            int four = rnd.Next(1, 49);
            int five = rnd.Next(1, 49);
            int six = rnd.Next(1, 49);
            int seven = rnd.Next(1, 49);

            if ((one == two) | (one == three) | (one == four) | (one == five) | (one == six) | (one == seven))
            {
                one = rnd.Next(1, 49);
            }

            if ((two == one) | (two == three) | (two == four) | (two == five) | (two == six) | (two == seven))
            {
                two = rnd.Next(1, 49);
            }

            if ((three == one) | (three == two) | (three == four) | (three == five) | (three == six) | (three == seven))
            {
                three = rnd.Next(1, 49);
            }

            if ((four == one) | (four == two) | (four == three) | (four == five) | (four == six) | (four == seven))
            {
                four = rnd.Next(1, 49);
            }

            if ((five == one) | (five == two) | (five == three) | (five == four) | (five == six) | (five == seven))
            {
                five = rnd.Next(1, 49);
            }

            if ((six == one) | (six == two) | (six == three) | (six == four) | (six == five) | (six == seven))
            {
                six = rnd.Next(1, 49);
            }

            if ((seven == one) | (seven == two) | (seven == three) | (seven == four) | (seven == five) | (seven == six))
            {
                seven = rnd.Next(1, 49);
            }


            List<int> numberList = new List<int>();

            List<int> numberListNoDuplicates = new List<int>();


            numberList.Add(one);
            numberList.Add(two);
            numberList.Add(three);
            numberList.Add(four);
            numberList.Add(five);
            numberList.Add(six);
            numberList.Add(seven);

            numberList.Sort();


            result = numberList[0].ToString() + "  " + numberList[1].ToString() + "  " + numberList[2].ToString() + "  " + numberList[3].ToString() + "  " + numberList[4].ToString() + "  " + numberList[5].ToString() + "  " + numberList[6].ToString();
            numberStringT.Add(result);
            numberList.Clear();
            result = "";
            rnd.Next();
        }


        //lblRandomNumber.Text = result;
        lblRandomNumber.Text = numberStringT[0];
        lblRandomNumber2.Text = numberStringT[1];
    }

1 个答案:

答案 0 :(得分:3)

将此内容移到for循环之前/之外:

 Random rnd = new Random();