C#掷骰子程序如何实现所有投掷结果相同时终止while循环
C# 掷骰子程序修改方案
核心实现逻辑
- 每次进入while循环后先创建临时
List<int>存储当前轮次所有骰子的投掷结果 - 投掷每个骰子时同时把值写入临时列表,再做输出
- 单轮投掷完成后,校验列表中所有值是否和第一个值相等,相等则终止循环
- 调整计数逻辑,原代码
count统计的是累计投掷的骰子总个数,修改为统计尝试轮次,匹配输出的attempts语义
修改后的完整代码
using System; using System.Collections.Generic; using System.Linq; // 新增引用,用All方法做判断更简洁 namespace AnyDice { class Program { static void Main(string[] args) { int diceSides; int rollDie; int count = 0; // 统计尝试轮次 bool keepRolling = true; List<int> num = new List<int>(); Random random = new Random(); Console.Write("Write the number of sides of your die: "); diceSides = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Type the numbers of the die"); for (int i = 0; i < diceSides; i++) { int rank = 1 + i; Console.Write(rank + "~~> "); num.Add(Convert.ToInt32(Console.ReadLine())); } num.Sort(); Console.WriteLine("\nHere's the die and its contents"); for (int i = 0; i < num.Count; i++) { Console.Write("["); Console.Write(num[i]); Console.Write("]"); } Console.WriteLine("\nHow many times do you want to roll at once"); rollDie = Convert.ToInt32(Console.ReadLine()); while (keepRolling) { count++; // 每轮开始计数+1 List<int> currentRolls = new List<int>(); // 存储当前轮次所有骰子结果 for (int i = 0; i < rollDie; i++) { int rollValue = num[random.Next(num.Count)]; currentRolls.Add(rollValue); // 先存值 Console.Write($"[{rollValue}]"); // 再输出 } Console.WriteLine(); // 轮次输出完换行 // 判断所有值是否一致 if (currentRolls.All(v => v == currentRolls[0])) { keepRolling = false; Console.WriteLine("所有骰子点数相同,终止投掷!"); } else { Console.ReadLine(); // 不一致时按回车继续下一轮 } } Console.WriteLine("It took you " + count + " attempts"); Console.ReadLine(); } } }
无Linq兼容实现方案
如果不想引入Linq的All方法,可以手动遍历判断,替换上面的一致性校验逻辑即可:
bool allSame = true; int firstValue = currentRolls[0]; foreach(int val in currentRolls) { if(val != firstValue) { allSame = false; break; } } if(allSame) { keepRolling = false; Console.WriteLine("所有骰子点数相同,终止投掷!"); }
内容的提问来源于stack exchange,提问作者beats
相关产品推荐
相关产品推荐

