I'm brand new to Erlang. How do you do modulo (get the remainder of a division)? It's % in most C-like languages, but that designates a comment in Erlang.
Several people answered with rem, which in most cases is fine. But I'm revisiting this because now I need to use negative numbers and rem gives you the remainder of a division, which is not the same as modulo for negative numbers.
8条答案
按热度按时间9vw9lbht1#
在Erlang中,
5 rem 3.
给出2
,-5 rem 3.
给出-2
。如果我理解你的问题,你会希望-5 rem 3.
给出1,因为-5 = -2 * 3 + 1.
这是你想要的吗?
woobm2wo2#
Erlang模运算符是
rem
0vvn1miw3#
我用了以下药剂:
zvokhttg4#
根据this blog post,它是
rem
。9bfwbjaz5#
上面的Y + X雷姆Y似乎错了:(Y + X)rem Y或Y +(X rem Y)产生不正确的结果。例如:设Y=3。如果X= -4,第一种形式返回-1,如果X=-3,第二种形式返回3,它们都不在[0; 3[.
我用这个代替:
n6lpvg4x6#
Erlang余数不适用于负数,因此您必须为负数参数编写自己的函数。
brccelvz7#
wz3gfoph8#
The accepted answer is wrong.
rem
behaves exactly like the%
operator in modern C. It uses truncated division.The accepted answer fails for X<0 and Y<0. Consider
mod(-5,-3)
:The alternative implementations for the modulo operator use floored division and Euclidean division. The results for those are
So
doesn't reproduce any modulo operator for X < 0 and Y < 0.
And
rem
works as expected -- it's using truncated division.