如何将随机数存储到数组中,但前提是数组中没有重复数?我下面的代码仍然输入重复的数字。

        Random rand = new Random();
        int[] lotto = new int [6];

        for (int i = 0; i < lotto.Length; i++)
        {
            int temp = rand.Next(1, 10);
            while (!(lotto.Contains(temp)))//While my lotto array doesn't contain a duplicate
            {
                lotto[i] = rand.Next(1, 10);//Add a new number into the array
            }
            Console.WriteLine(lotto[i]+1);
        }

最佳答案

试试这个:

Random rand = new Random();
int[] lotto = new int[6];

for (int i = 0; i < lotto.Length; i++)
{
    int temp = rand.Next(1, 10);

    // Loop until array doesn't contain temp
    while (lotto.Contains(temp))
    {
        temp = rand.Next(1, 10);
    }

    lotto[i] = temp;
    Console.WriteLine(lotto[i] + 1);
}


这样,代码会一直生成一个数字,直到找到一个不在数组中的数字,然后分配它并继续前进。

有很多方法可以“随机”排列数组,但是希望这可以解决您的代码问题。

10-08 14:04