Basic Pascal Tutorial/Chapter 3/IF/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,�解起�会很费劲。

�需�注�,代�缩进便于阅读代�(编译器忽略缩进)。

上一页 目录 下一页