【问题标题】:How to have multiple conditionals in an if statement in Ada如何在 Ada 的 if 语句中包含多个条件
【发布时间】:2016-04-28 23:48:53
【问题描述】:
如何在 if 语句中包含多个条件?
例如。程序向用户提出了一组问题:
1.) 输入 0 到 1000 之间的高度
(用户输入数据)
2.) 输入 0 到 500 之间的速度
(用户输入数据)
3.) 输入 0 到 200 之间的温度
(用户输入数据)
然后程序打印回来
- 高度=用户价值
- 速度=用户价值
- 温度 = 用户值 //忽略那些列表编号
我在我的 (.ads) 文件中设置了这些范围中的每一个都有一个批评值。
我想创建一个包含多个条件的 if 语句。
伪:如果速度 = 临界速度 & 温度 = 临界温度 & 高度 = 临界高度
然后打印(“一些消息”)
否则什么都不做
【问题讨论】:
标签:
if-statement
conditional
ada
【解决方案1】:
syntax of an if-statement 是
if_statement ::=
if condition then
sequence_of_statements
{elsif condition then
sequence_of_statements}
[else
sequence_of_statements]
end if;
syntax of “condition” 是
condition ::= boolean_expression
(即恰好是布尔值的表达式); syntax of “expression” 是
expression ::=
relation {and relation} | relation {and then relation}
| relation {or relation} | relation {or else relation}
| relation {xor relation}
所以你的代码看起来像
if velocity = critical_velocity
and temperature = critical_temperature
and altitude = critical_altitude
then
print ("some message”);
else
null;
end if;
你可以省略else 子句,你可以说and then 而不是普通的and,如果由于某种原因你不应该检查条件的其余部分,如果第一部分已经是False。这称为短路评估,它不是 Ada 中的默认值(它在 C 中)。
if X /= 0 and Y / X > 2 then
即使 X 为 0,也会评估 Y / X。
【解决方案2】:
在 Ada 中,您将使用 and、or 和 not 布尔运算符:
if Velocity = Critical_Velocity
and Temperature = Critical_Temperature
and Altitude = Critical_Altitude
then
Ada.Text_IO.Put_Line ("Crash");
else
...
end if;
当评估顺序很重要时,您将使用 然后 或 or else 语法(否则编译器可以更改优化顺序)。
表达式将按“然后”/“否则”的顺序进行计算。
if Velocity = Critical_Velocity
and then Temperature = Critical_Temperature
and then Altitude = Critical_Altitude
then
Ada.Text_IO.Put_Line ("Crash");
else
...
end if;
or else可以这样写:
if Velocity = Critical_Velocity
or else Temperature = Critical_Temperature
or else Altitude = Critical_Altitude
then
Ada.Text_IO.Put_Line ("Crash");
else
...
end if;
请注意,您不能将 and 和 or 混合在一起(因为这会给开发人员带来很多困惑)。
如果你这样做,你必须使用括号括起来。
if (Velocity = Critical_Velocity and Temperature = Critical_Temperature)
or else Altitude = Critical_Altitude
then
Ada.Text_IO.Put_Line ("Crash");
else
...
end if;