Fortran - 逻辑运算符



下表显示了 Fortran 支持的所有逻辑运算符。假设变量A 为 .true.,变量B 为 .false.,则:

运算符 描述 示例
.and. 称为逻辑与运算符。如果两个操作数都非零,则条件为真。 (A .and. B) 为假。
.or. 称为逻辑或运算符。如果两个操作数中的任何一个非零,则条件为真。 (A .or. B) 为真。
.not. 称为逻辑非运算符。用于反转其操作数的逻辑状态。如果条件为真,则逻辑非运算符将使其为假。 !(A .and. B) 为真。
.eqv. 称为逻辑等价运算符。用于检查两个逻辑值的等价性。 (A .eqv. B) 为假。
.neqv. 称为逻辑非等价运算符。用于检查两个逻辑值的非等价性。 (A .neqv. B) 为真。

示例

尝试以下示例以了解 Fortran 中可用的所有逻辑运算符:

program logicalOp
! this program checks logical operators
implicit none

   ! variable declaration
   logical :: a, b
   
   ! assigning values
   a = .true.
   b = .false.
   
   if (a .and. b) then
      print *, "Line 1 - Condition is true"
   else
      print *, "Line 1 - Condition is false"
   end if
   
   if (a .or. b) then
      print *, "Line 2 - Condition is true"
   else
      print *, "Line 2 - Condition is false"
   end if
   
   ! changing values
   a = .false.
   b = .true.
   
   if (.not.(a .and. b)) then
      print *, "Line 3 - Condition is true"
   else
      print *, "Line 3 - Condition is false"
   end if
   
   if (b .neqv. a) then
      print *, "Line 4 - Condition is true"
   else
      print *, "Line 4 - Condition is false"
   end if
   
   if (b .eqv. a) then
      print *, "Line 5 - Condition is true"
   else
      print *, "Line 5 - Condition is false"
   end if
   
end program logicalOp

编译并执行上述程序后,将产生以下结果:

Line 1 - Condition is false
Line 2 - Condition is true
Line 3 - Condition is true
Line 4 - Condition is true
Line 5 - Condition is false
fortran_operators.htm
广告