位置:首頁 > 高級語言 > Fortran教學 > Fortran關係運算符

Fortran關係運算符

下表列出了所有的Fortran支持的關係運算符。假設變量A=10和變量B=20,則:

操作符 等同 描述 示例
== .eq. 檢查兩個操作數的值相等與否,如果是,則條件變為真。 (A == B) i不為 true.
/= .ne. 檢查,兩個操作數的值相等與否,如果值不相等,則條件變為真。 (A != B) 為 true.
> .gt. 檢查,左操作數的值大於右操作數的值,如果是的話那麼條件為真。 (A > B)不為true.
< .lt. 檢查,左操作數的值是否小於右操作數的值,如果是的話那麼條件為真。 (A < B) 是 true.
>= .ge. 檢查,左邊的操作數的值是否大於或等於右操作數的值,如果是,則條件變為真。 (A >= B) 不為 true.
<= .le. 檢查,左邊的操作數的值是否小於或等於右操作數的值,如果是,則條件變為真。 (A <= B) 為 true.

示例

試試下麵的例子就明白所有在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