为什么 Elixir 中的 Rem 运算符 returns 负数?
Why Rem operator in Elixir returns negative numbers?
我正在尝试一个简单的操作
rem(-1, 25)
我希望这是整数除法和 return 24(与 Ruby 相同)但它 returns -1 的提醒。
难道我做错了什么?长生不老药的行为是否被打破?
余数的符号实际上因编程语言而异:https://en.wikipedia.org/wiki/Modulo_operation。所以两者都对,也都错。 :)
Ruby:
irb > -1.remainder(25)
=> -1
长生不老药:
iex(6)> rem(-1,25)
-1
它们的工作原理相同。
但我认为你的意思是 Ruby 的模:
irb > -1.modulo(25)
=> 24
如果您需要一个像这样的函数,那么我认为您需要自己编写 discussed here。
根据 Davis Thomas 在 Programming Elixir 中的说法:
rem is the remainder operator. It is called as a function (rem(11, 3) => 2). It
differs from normal modulo operations in that the result will have the
same sign as the function’s first argument.
这意味着,在您的情况下,即 rem(-1, 25),结果将带有 - 符号,如第一个参数。
我正在尝试一个简单的操作
rem(-1, 25)
我希望这是整数除法和 return 24(与 Ruby 相同)但它 returns -1 的提醒。 难道我做错了什么?长生不老药的行为是否被打破?
余数的符号实际上因编程语言而异:https://en.wikipedia.org/wiki/Modulo_operation。所以两者都对,也都错。 :)
Ruby:
irb > -1.remainder(25)
=> -1
长生不老药:
iex(6)> rem(-1,25)
-1
它们的工作原理相同。
但我认为你的意思是 Ruby 的模:
irb > -1.modulo(25)
=> 24
如果您需要一个像这样的函数,那么我认为您需要自己编写 discussed here。
根据 Davis Thomas 在 Programming Elixir 中的说法:
rem is the remainder operator. It is called as a function (rem(11, 3) => 2). It differs from normal modulo operations in that the result will have the same sign as the function’s first argument.
这意味着,在您的情况下,即 rem(-1, 25),结果将带有 - 符号,如第一个参数。