如何在 Elixir 中使用模运算符?
例如,在 Ruby 中你可以这样做:
5 % 2 == 0
它与 Ruby 的模运算符有何不同?
最佳答案
对于整数,请使用 Kernel.rem/2
:
iex(1)> rem(5, 2)
1
iex(2)> rem(5, 2) == 0
false
来自文档:
Computes the remainder of an integer division.
rem/2
uses truncated division, which means that the result will always have the sign of thedividend
.Raises an
ArithmeticError
exception if one of the arguments is not an integer, or when thedivisor
is 0.
与 Ruby 相比的主要区别似乎是:
rem
仅适用于整数,但%
会根据数据类型完全改变其行为。- Elixir 中负股息的符号为负(与 Ruby 的
remainder
相同):
ruby :
irb(main):001:0> -5 / 2
=> -3
irb(main):002:0> -5 % 2
=> 1
irb(main):003:0> -5.remainder(2)
=> -1
Elixir :
iex(1)> -5 / 2
-2.5
iex(2)> rem(-5, 2)
-1
Elixir 的 rem
只是使用 Erlang 的 rem
,所以 this related Erlang question可能也有用。
关于elixir - Elixir 中的模运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54790570/