本文介绍了产生随机数并插入阵列时不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  Random数发生器在C#中 - 唯一值

我试图写一个C#程序,将产生一个随机数,检查,如果这个数字是在我的数组,如果是,重复产生号码,否则插入这个数字到插槽 [我] 我的数组中。

I'm trying to write a C# program that will generate a random number, check if this number is in my array, if it is, repeat generating the number, else insert this number into slot [i] of my array.

下面是我的code迄今:

Here is my code so far:

        int check = 0;


        Random rand = new Random();

        int[] lotto = new int[6];



        for (int i = 0; i < lotto.Length; )
        {
            check = rand.Next(1, 41);
            while (!(lotto.Contains(check)))
            {

                lotto[i] = check;
                i++;
            }

            Console.WriteLine("slot " + i + " contains " + check);

        }
        Console.Read();
    }

更新:感谢想通了,取而代之的是如果与同时:)

UPDATE: Thanks figured it out, replaced the if with while :)

推荐答案

我猜你的问题是什么是不工作,我猜你已经忘记了一和使用的未声明的变量 I

I'm Guessing your question is what is not working, I am guessing that you have forgotten one ! and used an undeclared variable i:

if (!lotto.Contains(check)) // Ensure the number has not been chosen
{
    lotto[count] = check; // Set the number to its correct place
    count=count+1
}

这篇关于产生随机数并插入阵列时不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:25