gpt4 book ai didi

elixir - Elixir 中的模运算符

转载 作者:行者123 更新时间:2023-12-02 03:07:04 25 4
gpt4 key购买 nike

如何在 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 the dividend.

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

与 Ruby 相比的主要区别似乎是:

  1. rem 仅适用于整数,但 % 会根据数据类型完全改变其行为。
  2. 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com