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
廣告
© . All rights reserved.