Fortran - if-else if-else 構造



if 語句構造可以有一個或多個可選 else-if 構造。當 if 條件不滿足時,會立即執行緊隨其後的 else-if。如果 else-if 也不滿足,則會執行其繼任 else-if 語句(如果有),依此類推。

可選 else 放在末尾,並且會在以上任何條件都不成立時執行它。

  • 所有 else 語句(else-if 和 else)都是可選的。

  • else-if 可以使用一次或多次。

  • else 必須始終放在構造的末尾,並且只能出現一次。

語法

if...else if...else 語句的語法為 -

[name:] 
if (logical expression 1) then 
   ! block 1   
else if (logical expression 2) then       
   ! block 2   
else if (logical expression 3) then       
   ! block 3  
else       
   ! block 4   
end if [name]

示例

program ifElseIfElseProg
implicit none

   ! local variable declaration
   integer :: a = 100
 
   ! check the logical condition using if statement
   if( a == 10 ) then
  
      ! if condition is true then print the following 
      print*, "Value of a is 10" 
   
   else if( a == 20 ) then
  
      ! if else if condition is true 
      print*, "Value of a is 20" 
  
   else if( a == 30 ) then
   
      ! if else if condition is true  
      print*, "Value of a is 30" 
  
   else
   
      ! if none of the conditions is true 
      print*, "None of the values is matching" 
      
   end if
   
   print*, "exact value of a is ", a
 
end program ifElseIfElseProg

當編譯並執行以上程式碼時,將生成以下結果 -

None of the values is matching
exact value of a is 100
fortran_decisions.htm
廣告