Sign in Join
Wiki copytemporary

Revision 1 of 1, by Kai Burghardt on 8-20-2022. The page as it is now.

Basic Pascal Tutorial/Chapter 3/IF/zh CN

3Ca - IF语句 (原作者: Tao Yue, 状态: 未更改)

IF 语句,计算表达式结果进行分支。单行格式为:

pascal
if 表达� then
  语�;

如果表达式结果为真,则执行该语句,否则跳过。

IF 只接受一条语句;如果需要执行多条语句,则必须使用 begin-end:

pascal
if 表达� then
begin
  语�1;
  语�2
end;

当不满足条件时,还有一个选择:

pascal
if 表达� then
  为真
else
  为�;

表达式运算结果为假,则执行 else 后面的语句。 注意 else 前面没有分号,因为分号是两个语句之间的分隔符,而 else 并非语句。 如果在该处添了分号,则在编译的时候就会认为 if 语句到此结束,而把 else 当作另一句的开头。

如果有多个条件,只需要嵌套 if 语句:

pascal
if æ�¡ä»1 then
  语�1
else
  if æ�¡ä»1 then
    语�2
  else
    语�3;

小心使用嵌套,程序运行结果可能不是你想要的。

pascal
if æ�¡ä»1 then
  if æ�¡ä»2 then
    语�2
else
  语�1;

else 总是匹配与它最近的 if:

pascal
if æ�¡ä»1 then
  if æ�¡ä»2 then
    语�2
  else
    语�1;

你可以使用空语句:

pascal
if æ�¡ä»1 then
  if æ�¡ä»2 then
    语�2
  else
else
  语�1;

或者你可以使用 begin-end,但代码整洁的最佳方法是将条件重写。

pascal
if not æ�¡ä»1 then
  语�1
else
  if æ�¡ä»2 then
    语�2;

如果表达式像这样:(not(a < b) or (c + 3 > 6)) and g,理解起来会很费劲。

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

上一页 目录 下一页

From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 3/IF/zh CN", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.