![fee3908758bbeb7d9b06a61e737e80a6.png](https://img-blog.csdnimg.cn/img_convert/fee3908758bbeb7d9b06a61e737e80a6.png)
算术运算
除了加、减、乘、除等常见的运算之外,Lua还支持取整除法、取模和指数运算。
print(-1 + 3) -- 3print(0.1 + 0.2 == 0.3) -- false 和C语言类似浮点运算不精确,相等判断会有问题print(1 - 2) -- -1print(2 * 3) -- 6print(5 / 2) -- 2.5print(5 // 2) -- 2 Lua5.3引入print(5 % 3) -- 2print(-5 % 3) -- 1print(2 ^ 3) -- 8
Lua中除法的结果都是浮点数(即使两个操作数都是整数,且能整除),如果想要得到向下取整的结果,可以用math.floor()函数。Lua5.3为这种向下取整的除法引入了一个新的运算符//,对除法得到的结果向负无穷取整。
print(math.type(4 / 2)) -- float print(math.floor(5 / 2)) -- 2print(math.type(math.floor(5 / 2))) -- integer -- 注意,Lua5.3之前所有的数值类型都浮点数,5.3才引入整数print(-9 // 2) -- -5
取模运算需要注意有负数的情况,和其他语言有可能得出的结果不同,Lua的计算方法如下:
a % b == a - ((a // b