Lisp - 算術運算子



下表顯示了 LISP 支援的所有算術運算子。假設變數A值為 10,變數B值為 20,則:

運算子 描述 示例
+ 將兩個運算元相加 (+ A B) 結果為 30
- 從第一個運算元中減去第二個運算元 (- A B) 結果為 -10
* 將兩個運算元相乘 (* A B) 結果為 200
/ 將分子除以分母 (/ B A) 結果為 2
mod, rem 模運算子和整數除法後的餘數 (mod B A) 結果為 0
incf 自增運算子,將整數值增加指定第二個引數的值 (incf A 3) 結果為 13
decf 自減運算子,將整數值減少指定第二個引數的值 (decf A 4) 結果為 6

示例 - 算術運算子

建立一個名為 main.lisp 的新原始碼檔案,並在其中鍵入以下程式碼。

main.lisp

; set a as 10
(setq a 10)
; set b as 20
(setq b 20)
; perform sum 
(format t "~% A + B = ~d" (+ a b))
; perform substraction
(format t "~% A - B = ~d" (- a b))
; perform product
(format t "~% A x B = ~d" (* a b))
; perform multiplication
(format t "~% B / A = ~d" (/ b a))

輸出

單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回結果:

A + B = 30
A - B = -10
A x B = 200
B / A = 2

示例 - 自增/自減運算子

更新 main.lisp 並鍵入以下程式碼:

main.lisp

; set a as 10
(setq a 10)
; increment a by 3
(format t "~% Increment A by 3 = ~d" (incf a 3))
; decrement a by 4
(format t "~% Decrement A by 4 = ~d" (decf a 4))

輸出

單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回結果:

Increment A by 3 = 13
Decrement A by 4 = 9

示例 - 模/餘數運算子

更新 main.lisp 並鍵入以下程式碼:

main.lisp

; set a as 10
(setq a 10)
; Modulus of a by 3
(format t "~% Mod A by 3 = ~d" (mod a 3))
; Remainder of a by 3
(format t "~% Rem A by 3 = ~d" (rem a 3))

輸出

單擊“執行”按鈕或鍵入 Ctrl+E 時,LISP 會立即執行它,並返回結果:

Mod A by 3 = 1
Rem A by 3 = 1
lisp_operators.htm
廣告