当前位置: 首页 > 文档资料 > Fortran 中文教程 >

If… then...else construct

优质
小牛编辑
127浏览
2023-12-01

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

语法 (Syntax)

>

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将执行else块内的代码块。

流程图 (Flow Diagram)

流程图1

例子 (Example)

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