【发布时间】:2022-03-07 03:10:18
【问题描述】:
我目前正在用 C# 制作的控制台窗口中开发一个小型彩票游戏。
我添加了一个功能,让用户随机化他将在他的票上拥有的 6 个数字,但注意到我的随机数生成器有时会生成相同的数字,即使理论上你只能有一个数字一次,所以我构建了这个检查来看看是否有任何数字相同,只是注意到我不能回到随机化一个新的数字列表,因为goto 函数不能退出循环(CS0159)。还有其他方法吗?
代码:
Console.WriteLine("\nRandomized 6 numbers: ");
// Randomize 6 numbers in for the array randomList
for (int z = 0; z <= 5; z++)
{
SameNum:
int rndNum = rnd.Next(1, 50);
randomList[z] = rndNum;
}
// Once the list is done check if any elements of the array
// are the same and if yes go back to SameNum to generate a new
// List of 6 numbers
for (int a = 0; a <= 5; a++)
{
for (int b = 0; b <= 5; b++)
{
while (randomList[a] == randomList[b])
{
goto SameNum;
}
}
}
// Display the random list if there are no same numbers
for (int c = 0; c <= 5; c++)
{
Console.WriteLine(randomList[c] + " ");
}
【问题讨论】:
-
99.9% 的情况下,如果您在 c# 中使用
goto,那么您做错了什么。以不需要使用goto的方式重构您的代码 - 将该代码与另一种方法分开,这是一种简单的重构方法,而且可能是一种聪明的方法。 -
生成号码时为什么不检查号码?
-
@AndrewMorton 是的,这真的很有用,不知道为什么我之前没有想到这个,谢谢!
-
您可以跳出循环。但是,您不能转到 进入 循环。
标签: c# arrays for-loop random goto