跳轉到內容

程式設計基礎/邏輯運算子

來自華夏公益教科書,開放的書籍,構建開放的世界

邏輯運算子是一種符號或詞語,用於連線兩個或多個表示式,使得生成的複合表示式的值僅取決於原始表示式的值和運算子的含義。[1] 常見的邏輯運算子包括 AND、OR 和 NOT。

在大多數語言中,產生布爾資料型別值的表示式分為兩組。一組在表示式中使用關係運算符,另一組在表示式中使用邏輯運算子。

邏輯運算子通常用於幫助建立控制程式流的測試表達式。這種型別的表示式也稱為布林表示式,因為它們在評估時會產生布爾答案或值。有三個常見的邏輯運算子透過操作其他布林運算元來給出布林值。運算子符號和/或名稱因不同的程式語言而異。

語言 AND OR NOT
C++ && || !
C# && || !
Java && || !
JavaScript && || !
Python and or not
Swift && || !

豎線或管道符號與反斜槓 \ 在同一個鍵上。使用 SHIFT 鍵來獲取它。它位於大多數鍵盤上的 Enter 鍵上方。在某些鍵盤上它可能是一條實線,在某些印刷字型中顯示為實線。

在大多數語言中,都有嚴格的規則來形成正確的邏輯表示式。例如:

6 > 4 && 2 <= 14

6 > 4 and 2 <= 14

此表示式有兩個關係運算符和一個邏輯運算子。使用運算子優先順序規則,兩個“關係比較”運算子將在“邏輯與”運算子之前完成。因此

true && true

True and True

表示式的最終評估結果為:true。

我們可以用英語說:六大於四,二小於或等於十四,這是真的。

在形成邏輯表示式時,程式設計師經常使用圓括號(即使從技術上講不需要),以使表示式的邏輯非常清晰。考慮上面重寫的複雜布林表示式

(6 > 4) && (2 <= 14)

(6 > 4) and (2 <= 14)

大多數程式語言將任何非零值識別為 true。這使得以下表達式有效

6 > 4 && 8

6 > 4 and 8

但請記住運算順序。用英語來說,這是六大於四,八不為零。因此

true && true

True and True

要將 6 與 4 和 8 進行比較,應改為寫成

6 > 4 && 6 > 8

6 > 4 and 6 > 8

這將被評估為 false,因為

true && false

True and False

真值表

[編輯 | 編輯原始碼]

真值表是顯示邏輯關係的一種常用方法。

邏輯 AND
x y x and y
false false false
false true false
true false false
true true true
邏輯 OR
x y x or y
false false false
false true true
true false true
true true true
邏輯 NOT
x not x
false true
true false

看看以下假設場景

AND

A mother tells her son, he must clean his room AND do his homework to go outside. If the son only does one of the tasks his mother asks of him, he will not be allowed outside because he has failed to complete the other task. 

記住本課中的內容,當使用 'AND' 語句時,相同的邏輯適用,程式將不會執行與 true 條件關聯的語句,除非 'AND' 語句中的所有條件都為 true。

OR

Karen is told she can get an 'A' if she writes an essay OR successfully hacks into the class gradebook. By saying OR the teacher has given Karen two possible ways to get an 'A'. Each way is entirely independent from the other so she does not have to do both tasks to get an 'A' only one. 

記住本課中的內容,當使用 'OR' 語句時,'OR' 語句中列出的條件只要有一個為 true,就會執行與 true 條件關聯的語句。

NOT

Mark is told he can only go to the club if he's NOT Steve. This is due to Steve being banned from the club for rowdy behavior. While Mark and Steve look a like, they are not the same person. Mark proves this by showing the bouncer his 'I.D.'. Since Mark is NOT Steve the bouncer lets him in and for the rest of the night he has a great time.

記住本課中的內容,當使用 'NOT' 語句時,程式會將任何與列出語句的值相等的值視為 false。只有與語句值 'NOT' 相等的情況才會執行為 true。


有道理吧?希望你能將這些應用到下面列出的表示式示例中。

示例

  • 25 < 7 || 15 > 36
  • 15 > 36 || 3 < 7
  • 14 > 7 && 5 <= 5
  • 4 > 3 && 17 <= 7
  • ! false
  • ! (13 != 7)
  • 9 != 7 && ! 0
  • 5 > 1 && 7

更多示例

  • 25 < 7 or 15 > 36
  • 15 > 36 or 3 < 7
  • 14 > 7 and 5 <= 5
  • 4 > 3 and 17 <= 7
  • not False
  • not (13 != 7)
  • 9 != 7 and not 0
  • 5 > 1 and 7


關鍵術語

[編輯 | 編輯原始碼]
邏輯運算子
用於建立複雜的布林表示式的運算子。
測試表達式
也稱為布林表示式。
真值表
顯示邏輯關係的一種常用方法。

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書