Fortran - If-then-else 构造


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

句法

>

if...then...else语句的基本语法是 -

if (logical expression) then      
   statement(s)  
else
   other_statement(s)
end if

但是,如果您为if块命名,则命名的if-else语句的语法将如下所示 -

[name:] if (logical expression) then      
   ! various statements           
   . . . 
   else
   !other statement(s)
   . . . 
end if [name]

如果逻辑表达式的计算结果为true,则将执行if...then语句内的代码块,否则将执行else块内的代码块。

流程图

流程图1

例子

program ifElseProg
implicit none
   ! local variable declaration
   integer :: a = 100
 
   ! check the logical condition using if statement
   if (a < 20 ) then
   
   ! if condition is true then print the following 
   print*, "a is less than 20"
   else
   print*, "a is not less than 20"
   end if
       
   print*, "value of a is ", a
	
end program ifElseProg

当上面的代码被编译并执行时,它会产生以下结果 -

a is not less than 20
value of a is 100
fortran_decisions.htm