if… then 语句可以后跟一个可选的 else 语句, 它执行时,逻辑表达式为假。
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]
如果逻辑表达式的计算结果为代码里面的 if ... then 语句会被执行,对 else 块中的代码,否则该块将被执行 else 块。
流程图
示例
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