math.fmod是否总等于math.mod?

我尝试使用以下代码找出 math.fmod 和 math.mod 之间的区别:

a={9.5 ,-9.5,-9.5,9.5}
b={-3.5, 3.5,-3.5,3.5}
for i=1,#a do
    if math.fmod(a[i],b[i])~=math.mod(a[i],b[i]) then
        print("yeah")
    end
end

它从未打印出 "yeah"! 我应该在数组a和b中放什么才能看到 "yeah"?

math.fmod() 的文档说明它返回 x 除以 y 的余数,该商朝零舍入。

原文链接 https://stackoverflow.com/questions/7077036

点赞
stackoverflow用户107090
stackoverflow用户107090

math.mod 是与 math.fmod _相同_的函数。实际上,math.mod 仅存在是为了与之前的版本兼容;它没有在手册中列出。在你的代码中尝试使用 math.modf 替代 math.mod

2011-08-16 12:26:52
stackoverflow用户2980952
stackoverflow用户2980952

Lua 中的取模运算被定义为“向负无穷方向取整的除法余数” - 链接在这里 - 这与 fmod 的定义不同(就像你在原帖中引用的那样)。

你真正需要做的是使用取模运算符(%)而不是 math.mod:

a={9.5 ,-9.5,-9.5,9.5}
b={-3.5, 3.5,-3.5,3.5}
for i=1,#a do
    if math.fmod(a[i],b[i]) ~= a[i] % b[i] then
        print("yeah")
    end
end
2013-11-11 22:10:35