Ada编程:如何在case语句中处理<2或>12的无效骰子点数
Ada case语句处理无效点数分支的解决方案
你的问题核心是如何在case语句中正确定义**无效点数(小于2或大于12)**的分支,同时满足题目要求用others处理点数roll。
Ada的case语句要求分支必须覆盖所有可能的取值,且分支之间不能重叠。针对你的需求,无效点数的分支可以用范围匹配来实现:when Integer'First .. 1 | 13 .. Integer'Last,这个表达式会匹配所有小于2和大于12的整数。
注意,这个分支必须放在others之前——因为others是匹配所有未被前面分支覆盖的取值。调整后的case语句逻辑如下:
- 先匹配赢的点数(7、11)
- 再匹配输的点数(2、3、12)
- 接着匹配无效点数(<2或>12)
- 最后用
others匹配剩下的有效点数(4、5、6、8、9、10),也就是点数roll
修改后的完整代码:
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Learning is Dice : Integer; -- the value of a roll begin Put_Line ("Enter the value of your roll of the dice"); Get (Dice); New_Line; Put("The number "); Put(Item => Dice, Width => 0); case Dice is when 7 | 11 => Put_Line ("is a winning dice roll"); when 2 | 3 | 12 => Put_Line ("is a losing dice roll"); when Integer'First .. 1 | 13 .. Integer'Last => Put_Line ("is not a valid dice roll"); when others => Put_Line ("establishes the point"); end case; New_Line; end Learning;
关键细节说明:
Integer'First是Integer类型的最小值,Integer'Last是最大值,这样写能确保覆盖所有小于2和大于12的整数,不受具体平台Integer取值范围的限制。- 分支顺序严格遵循逻辑优先级,
others必须作为最后一个分支,否则会触发编译错误。 - 所有分支互斥且覆盖了Integer的全部可能取值,完全符合Ada的语法规范。
内容的提问来源于stack exchange,提问作者user2669989
相关产品推荐
相关产品推荐

