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

嵌套 if 构造(nested if construct)

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

您可以在另一个ifelse if语句中使用ifelse if语句。

语法 (Syntax)

嵌套if语句的语法如下 -

if ( logical_expression 1) then
   !Executes when the boolean expression 1 is true 
   …
   if(logical_expression 2)then 
      ! Executes when the boolean expression 2 is true 
      …
   end if
end if

例子 (Example)

program nestedIfProg
implicit none
   ! local variable declaration
   integer :: a = 100, b= 200
   ! check the logical condition using if statement
   if( a == 100 ) then
   ! if condition is true then check the following 
   if( b == 200 ) then
   ! if inner if condition is true 
   print*, "Value of a is 100 and b is 200" 
   end if
   end if
   print*, "exact value of a is ", a
   print*, "exact value of b is ", b
end program nestedIfProg

编译并执行上述代码时,会产生以下结果 -

Value of a is 100 and b is 200
exact value of a is 100
exact value of b is 200