Basic Pascal Tutorial/Chapter 3/IF/zh CN

From Free Pascal wiki
(Redirected from IF/zh CN)
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

български (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,理解起来会很费劲。

仍需要注意,代码缩进便于阅读代码(编译器忽略缩进)。

上一页 目录 下一页