Difference between revisions of "Basic Pascal Tutorial/Chapter 3/IF/zh CN"
From Free Pascal wiki
Jump to navigationJump to searchm (Fixed syntax highlighting) |
|||
Line 5: | Line 5: | ||
<tt>IF</tt> 语句,计算表达式结果进行分支。单行格式为: | <tt>IF</tt> 语句,计算表达式结果进行分支。单行格式为: | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang=pascal> |
if 表达式 then | if 表达式 then | ||
语句; | 语句; | ||
Line 14: | Line 14: | ||
<tt>IF</tt> 只接受一条语句;如果需要执行多条语句,则必须使用 <tt>begin-end</tt>: | <tt>IF</tt> 只接受一条语句;如果需要执行多条语句,则必须使用 <tt>begin-end</tt>: | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang=pascal> |
if 表达式 then | if 表达式 then | ||
begin | begin | ||
Line 24: | Line 24: | ||
当不满足条件时,还有一个选择: | 当不满足条件时,还有一个选择: | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang=pascal> |
if 表达式 then | if 表达式 then | ||
为真 | 为真 | ||
Line 37: | Line 37: | ||
如果有多个条件,只需要嵌套 <tt>if</tt> 语句: | 如果有多个条件,只需要嵌套 <tt>if</tt> 语句: | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang=pascal> |
if 条件1 then | if 条件1 then | ||
语句1 | 语句1 | ||
Line 49: | Line 49: | ||
小心使用嵌套,程序运行结果可能不是你想要的。 | 小心使用嵌套,程序运行结果可能不是你想要的。 | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang=pascal> |
if 条件1 then | if 条件1 then | ||
if 条件2 then | if 条件2 then | ||
Line 60: | Line 60: | ||
<tt>else</tt> 总是匹配与它最近的 <tt>if</tt>: | <tt>else</tt> 总是匹配与它最近的 <tt>if</tt>: | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang=pascal> |
if 条件1 then | if 条件1 then | ||
if 条件2 then | if 条件2 then | ||
Line 70: | Line 70: | ||
你可以使用空语句: | 你可以使用空语句: | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang=pascal> |
if 条件1 then | if 条件1 then | ||
if 条件2 then | if 条件2 then | ||
Line 81: | Line 81: | ||
或者你可以使用 <tt>begin-end</tt>,但代码整洁的最佳方法是将条件重写。 | 或者你可以使用 <tt>begin-end</tt>,但代码整洁的最佳方法是将条件重写。 | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang=pascal> |
if not 条件1 then | if not 条件1 then | ||
语句1 | 语句1 | ||
Line 98: | Line 98: | ||
|[[CASE/zh_CN|下一页]] | |[[CASE/zh_CN|下一页]] | ||
|} | |} | ||
− | |||
− | |||
− |
Revision as of 11:15, 17 February 2020
│
български (bg) │
English (en) │
français (fr) │
日本語 (ja) │
中文(中国大陆) (zh_CN) │
3Ca - IF语句 (原作者: Tao Yue, 状态: 未更改)
IF 语句,计算表达式结果进行分支。单行格式为:
if 表达式 then
语句;
如果表达式结果为真,则执行该语句,否则跳过。
IF 只接受一条语句;如果需要执行多条语句,则必须使用 begin-end:
if 表达式 then
begin
语句1;
语句2
end;
当不满足条件时,还有一个选择:
if 表达式 then
为真
else
为假;
表达式运算结果为假,则执行 else 后面的语句。 注意 else 前面没有分号,因为分号是两个语句之间的分隔符,而 else 并非语句。 如果在该处添了分号,则在编译的时候就会认为 if 语句到此结束,而把 else 当作另一句的开头。
如果有多个条件,只需要嵌套 if 语句:
if 条件1 then
语句1
else
if 条件1 then
语句2
else
语句3;
小心使用嵌套,程序运行结果可能不是你想要的。
if 条件1 then
if 条件2 then
语句2
else
语句1;
else 总是匹配与它最近的 if:
if 条件1 then
if 条件2 then
语句2
else
语句1;
你可以使用空语句:
if 条件1 then
if 条件2 then
语句2
else
else
语句1;
或者你可以使用 begin-end,但代码整洁的最佳方法是将条件重写。
if not 条件1 then
语句1
else
if 条件2 then
语句2;
如果表达式像这样:(not(a < b) or (c + 3 > 6)) and g,理解起来会很费劲。
仍需要注意,代码缩进便于阅读代码(编译器忽略缩进)。
上一页 | 目录 | 下一页 |