Pascal - if then else 語句



一個if-then語句後面可以跟一個可選的else語句,當布林表示式為false時,該語句將執行。

語法

if-then-else 語句的語法如下:

if condition then S1 else S2;

其中,S1S2 是不同的語句。請注意,語句 S1 後面不跟分號。在 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計算結果為真,則執行 if-then 程式碼塊,否則執行 else 程式碼塊。

Pascal 將任何非零和非 nil 值視為真,如果值為零或 nil,則將其視為假值。

流程圖

Pascal if-then-else statement

示例

讓我們嘗試一個完整的示例來說明這個概念:

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

if-then-else if-then-else 語句

一個 if-then 語句後面可以跟一個可選的 else if-then-else 語句,這對於使用單個 if-then-else if 語句測試各種條件非常有用。

使用 if-then、else if-then、else 語句時,需要注意以下幾點。

  • 一個 if-then 語句可以有零個或一個 else,並且它必須出現在任何 else if 之後。

  • 一個 if-then 語句可以有零到多個 else if,並且它們必須出現在 else 之前。

  • 一旦某個 else if 成功,就不會測試任何剩餘的 else if 或 else。

  • 最後一個 else 關鍵字前沒有分號 (;),但所有語句都可以是複合語句。

語法

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 *)

示例

以下示例說明了這個概念:

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
pascal_decision_making.htm
廣告

© . All rights reserved.