<分区>
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 :)