Lua算術運算子範例

2019-10-16 23:12:42

下表顯示了Lua語言支援的所有算術運算子。 假設變數A=10,變數B=20,然後 -

運算子 描述 範例
+ 相加兩個運算元 A + B = 30
- 從第一個減去第二個運算元 A - B = -10
* 將兩個運算元相乘 A * B = 200
/ 用除分子除以分子 B / A = 2
% 模數運算子,整數除法後的餘數 B % A = 0
^ 指數運算子取指數冪值 A^2 = 100
- 一元,充當否定 -A = -10

範例

嘗試以下範例來了解Lua程式設計語言中可用的所有算術運算子 -

a = 21
b = 10
c = a + b

print("Line 1 - Value of c is ", c )
c = a - b

print("Line 2 - Value of c is ", c )
c = a * b

print("Line 3 - Value of c is ", c )
c = a / b

print("Line 4 - Value of c is ", c )
c = a % b

print("Line 5 - Value of c is ", c )
c = a^2

print("Line 6 - Value of c is ", c )
c = -a

print("Line 7 - Value of c is ", c )

執行上述程式時,會產生以下結果 -

Line 1 - Value of c is     31
Line 2 - Value of c is     11
Line 3 - Value of c is     210
Line 4 - Value of c is     2.1
Line 5 - Value of c is     1
Line 6 - Value of c is     441
Line 7 - Value of c is     -21