【发布时间】:2012-08-30 22:07:41
【问题描述】:
我正在尝试编写一个生成随机数的 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 :)
【问题讨论】:
-
为什么 SU 上有 C# 标签?
-
你的问题不是很清楚。你能详细说明你想要什么吗?
-
while (lotto.Contains(check)) check = rand.next(1, 41); lotto[i] = check;应该这样做... -
@PriscillaKorostchuk 这很容易实现,就在将新数字插入数组之前,检查它是否已经存在。如果是 - 跳过数字,并生成新的数字(确保您没有前进到数组中的下一个位置)。
-
不应该是
if (!lotto.Contains(check))和!,我想?在 C# 中,!表示“不是”。