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