Elixir中的模运算符 [英] Modulo operator in Elixir

查看:78
本文介绍了Elixir中的模运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Elixir中使用模运算符?

例如在Ruby中,您可以执行以下操作:

  5%2 == 0 

它与Ruby的模运算符有何不同?

解决方案

对于整数,请使用 Kernel.rem/2 :

  iex(1)>雷姆(5,2)1个iex(2)>rem(5,2)== 0错误的 

从文档中

计算整数除法的余数.

rem/2 使用截断法,这意味着结果将始终带有股息的符号.

如果参数之一不是整数,或者除数为0时.

与Ruby相比,主要区别在于:

  1. rem 仅适用于整数,但是完全根据数据类型更改其行为.
  2. 对于Elixir中的负股利,该符号为负(与Ruby的 其余 ):

Ruby:

  irb(main):001:0>-5/2=>-3irb(main):002:0>-5%2=>1个irb(main):003:0>-5.remainder(2)=>-1 

长生不老药:

  iex(1)>-5/2-2.5iex(2)>雷姆(-5,2)-1 

Elixir的 rem 仅使用Erlang的 rem ,因此 解决方案

For integers, use 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 the dividend.

Raises an ArithmeticError exception if one of the arguments is not an integer, or when the divisor is 0.

The main differences compared to Ruby seem to be:

  1. rem only works with integers, but % changes its behavior completely depending on the datatype.
  2. The sign is negative for negative dividends in Elixir (the same as Ruby's 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中的模运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆