Fortran - 如果 - 那么 - 别的构造



如果…那么语句后可以接一个可选的else 语句,当逻辑表达式为假时执行此语句。

语法

>

如果…那么…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 块中的代码块将被执行。

流程图

Flow Diagram1

示例

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
广告