目录

If-then-else statement

if-then语句后面可以跟一个可选的else语句,该语句在布尔表达式为false时执行。

语法 (Syntax)

if-then-else语句的语法是 -

if condition then S1 else S2;

其中, S1S2是不同的陈述。 Please note that the statement S1 is not followed by a semicolon 。 在if-then-else语句中,当测试条件为真时,执行语句S1并跳过S2; 当测试条件为假时,则绕过S1并执行语句S2。

例如,

if color = red then
   writeln('You have chosen a red car')
else
   writeln('Please choose a color for your car');

如果布尔表达式condition计算结果为true,那么将执行if-then代码块,否则将执行else代码块。

Pascal假定任何非零和非零值为true,如果它为零或零,则假定为假值。

流程图 (Flow Diagram)

Pascal if-then-else语句

例子 (Example)

让我们尝试一个完整的例子来说明这个概念 -

program ifelseChecking;
var
   { local variable definition }
   a : integer;
begin
   a := 100;
   (* check the boolean condition *)
   if( a < 20 ) then
      (* if condition is true then print the following *)
      writeln('a is less than 20' )
   else
      (* if condition is false then print the following *) 
      writeln('a is not less than 20' );
      writeln('value of a is : ', a);
end.

编译并执行上述代码时,会产生以下结果 -

a is not less than 20
value of a is : 100

The if-then-else if-then-else 语句

if-then语句之后可以跟一个可选的else if-then-else语句,这对于使用单个if-then-else if语句测试各种条件非常有用。

当使用if-then,else if-then,else语句时,要记住几点。

  • if-then语句可以有零个或一个其他语句,它必须在任何其他if之后。

  • if-then语句可以为零,如果是,则必须在else之前。

  • 一旦else成功,其余的其他if或者其他都将被测试。

  • 在最后一个else关键字之前没有给出分号(;),但所有语句都可以是复合语句。

语法 (Syntax)

Pascal编程语言中if-then-else if-then-else语句的语法是 -

if(boolean_expression 1)then 
   S1 (* Executes when the boolean expression 1 is true *)
else if( boolean_expression 2) then 
   S2 (* Executes when the boolean expression 2 is true *)
else if( boolean_expression 3) then 
   S3 (* Executes when the boolean expression 3 is true *)
else 
   S4; ( * executes when the none of the above condition is true *)

例子 (Example)

以下示例说明了这一概念 -

program ifelse_ifelseChecking;
var
   { local variable definition }
   a : integer;
begin
   a := 100;
   (* check the boolean condition *)
   if (a = 10)  then
      (* if condition is true then print the following *)
      writeln('Value of a is 10' )
   else if ( a = 20 ) then
      (* if else if condition is true *)
      writeln('Value of a is 20' )
   else if( a = 30 ) then 
      (* if else if condition is true  *)
      writeln('Value of a is 30' )
   else
      (* if none of the conditions is true *)
      writeln('None of the values is matching' );
      writeln('Exact value of a is: ', a );
end.

编译并执行上述代码时,会产生以下结果 -

None of the values is matching
Exact value of a is: 100
↑回到顶部↑
WIKI教程 @2018