【问题标题】:How to make goto statements when not in scope in C#?不在 C# 范围内时如何制作 goto 语句?
【发布时间】: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


【解决方案1】:

可能的解决方案。

 List<int> digits = new List<int>();
                int z= 0;
                while(z <= 5)
                {
                    int rndNum = rnd.Next(1, 50);
                    if(!digits.Contains(rndNum))
                    {
                       digits.Add(rnbNum); 
                      z++; 
                    }  
                }
    int[] randomList = digits.ToArray();
    digits.Clear();

【讨论】:

  • 嘿,所以我想我知道这是如何工作的,但我仍然会问我是否正确。这段代码创建了一个名为 digits 的列表,然后从 0 开始进行一个 while 循环,并生成一个介于 1 和 49 之间的随机数。然后它检查 digits 是否包含滚动数字。如果不是,它将生成的数字添加到列表中并添加 z++(表示第一个数字已完成)。如果数字确实包含生成的数字,它不会添加 z++ 并生成一个新数字。在生成 5 个不同的数字后,它将列表转换为数组并将其设置为 randomList?这就是代码的作用吗?谢谢^^
  • 另外,在将randomList 设置为digits.ToArray(); 完成后,我将如何删除列表中的所有数字,以便我可以再次玩,因为当您再次玩时,滚动的数字仍存储在列表中这样你就再也拿不到它们了。
  • digits.Clear()....
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多