Fortran - if-then 构造


if ...then语句由一个逻辑表达式组成,后跟一个或多个语句,并以end if语句终止。

句法

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

if (logical expression) then      
   statement  
end if

但是,您可以为if块命名,那么命名的if语句的语法将如下所示 -

[name:] if (logical expression) then      
   ! various statements           
   . . .  
end if [name]

如果逻辑表达式的计算结果为true,则if...then语句内的代码块将被执行。如果逻辑表达式的计算结果为false,则将执行if 语句结束后的第一组代码。

流程图

流程图

实施例1

program ifProg
implicit none
   ! local variable declaration
   integer :: a = 10
 
   ! 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"
   end if
       
   print*, "value of a is ", a
 end program ifProg

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

a is less than 20
value of a is 10

实施例2

这个例子演示了一个命名的if块 -

program markGradeA  
implicit none  
   real :: marks
   ! assign marks   
   marks = 90.4
   ! use an if statement to give grade
  
   gr: if (marks > 90.0) then  
   print *, " Grade A"
   end if gr
end program markGradeA   

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

Grade A
fortran_decisions.htm