print(15%6,math.fmod(15,6))
–输出:3 3
另外可以对小数进行求余运算:
print(3.1%1.5,math.fmod(3.1,1.5))
–输出:0.1 0.1
这样看来2个是没有区别的,但是:
print(-2%3,math.fmod(-2,3))
–输出:1,-2
因为 y%x运算总是将y/x的值向下取整,而math.fmod(y,x)是将y/x的值向0取整,所以-2%3得到的商是math.floor(-2/3)=-1,余数为1,
而math.fmod(-2,3)得到的商是math.ceil(-2/3)=0,余数是-2。
总之当y/x为负数数,%和math.floor会用不同的取整方式,故而有不同的余数。
另外,自己试了一下mod()和fmod()得出来的结果个人认为其实并没有区别,网上查了一下没找到相关的问题,如果有大佬知道其中的区别欢迎指出出来,
print(15%6,math.mod(15,6))
print(math.floor(15/6),math.fmod(15,6),math.mod(15,6))
print(math.ceil(15/6),math.fmod(15,6),math.mod(15,6))
print(3.1%1.5,math.fmod(3.1,1.5),math.mod(3.1,1.5))
print(-2%3,math.fmod(-2,3),math.mod(-2,3))
print(-2%-3,math.fmod(-2,-3),math.mod(-2,-3))
print(2%-3,math.fmod(2,-3),math.mod(2,-3))
输出:
>lua -e "io.stdout:setvbuf 'no'" "mathTest.lua"
3 3
2 3 3
3 3 3
0.1 0.1 0.1
1 -2 -2
-2 -2 -2
-1 2 2
>Exit code: 0