[英]Modulo operator in Elixir
How do I use the modulo operator in Elixir? 如何在Elixir中使用模运算符?
For example in Ruby you can do: 例如在Ruby中,您可以:
5 % 2 == 0
How does it differ from Ruby's modulo operator? 它与Ruby的模运算符有何不同?
Use rem/2
see: https://hexdocs.pm/elixir/Kernel.html#rem/2 So in Elixir your example becomes: 使用rem/2
请参阅: https : //hexdocs.pm/elixir/Kernel.html#rem/2因此,在Elixir中,您的示例变为:
rem(5,2) == 0
which returns false
返回false
BTW what you wrote using %
in Elixir simply starts a comment to the end of the line. 顺便说一下你在Elixir中使用%
编写的内容只是在行尾开始发表评论。
For integers, use Kernel.rem/2
: 对于整数,使用Kernel.rem/2
:
iex(1)> rem(5, 2)
1
iex(2)> rem(5, 2) == 0
false
From the docs: 来自文档:
Computes the remainder of an integer division. 计算整数除法的余数。
rem/2
uses truncated division, which means that the result will always have the sign of thedividend
.rem/2
使用截断除法,这意味着结果将始终具有dividend
的符号。Raises an
ArithmeticError
exception if one of the arguments is not an integer, or when thedivisor
is 0. 如果其中一个参数不是整数,或者divisor
为0,则引发ArithmeticError
异常。
The main differences compared to Ruby seem to be: 与Ruby相比的主要差异似乎是:
rem
only works with integers, but %
changes its behavior completely depending on the datatype. rem
仅适用于整数,但%
根据数据类型完全改变其行为。 remainder
): 对于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's rem
just uses Erlang's rem
, so this related Erlang question may also be useful. Elixir的rem
只使用Erlang的rem
,所以这个相关的Erlang问题也可能有用。
Use Integer.mod/2
, see: https://hexdocs.pm/elixir/Integer.html#mod/2 使用Integer.mod/2
,请参阅: https : //hexdocs.pm/elixir/Integer.html#mod/2
iex>Integer.mod(-5, 2)
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.