c# - 生成随机数并无重复地插入数组

标签 c# arrays random

<分区>

Possible Duplicate:
Random number generator in C# - unique values

我正在尝试编写一个 C# 程序来生成一个随机数,检查这个数字是否在我的数组中,如果是,重复生成该数字,否则将这个数字插入插槽 [i] 我的数组。

到目前为止,这是我的代码:

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

更新:谢谢想通了,用 while 替换了 if :)

最佳答案

我猜你的问题是什么不起作用,我猜你忘记了一个 ! 并使用了一个未声明的变量 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
}

关于c# - 生成随机数并无重复地插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12294128/

相关文章:

c# - 使用 WCF ResponseFormat = WebMessageFormat.Json 时忽略类的属性

c# - 无法将类型 'Microsoft.SolverFoundation.Services.Term' 隐式转换为 'bool'

c - 重新分配**数组

c# - 为什么完全使用 C# 类 System.Random 而不是 System.Security.Cryptography.RandomNumberGenerator?

python - 使用随机时,哪种形式返回相同的 50% 机会?

c# - ObjectListView 全选复选框

c# - 如何在 C# 中使循环体并行运行

c++ - C++ 中的函数指针数组

javascript - 我想在 Chart.js 中显示一个折线栏,其中的数据自动从 mockapi 获取

assembly - 从 6502 汇编器获取随机数