Clojure中mod和rem的区别

Ert*_*tin 12 clojure clojurescript

我无法理解这两个(mod&rem)函数之间的区别.

Pio*_*dyl 12

Clojuredoc的例子rem描述了差异:

;; rem and mod are commonly used to get the remainder.
;; mod means Gaussian mod, so the result is always
;; non-negative.  Don't confuse it with ANSI C's %
;; operator, which despite being pronounced
;; 'mod' actually implements rem, i.e. -10 % 3 = -1.

user=> (mod -10 3)
2

user=> (rem -10 3)
-1
Run Code Online (Sandbox Code Playgroud)


Ada*_*Lee 12

mod返回所述第一数目,最大的区别整数小于所述第一数目的第二数目的(可能为负)多个:
rem仅仅是余数.

例如,(rem -4 3) => -1这里不足为奇:-4除以3为-1,其中-1为"剩余".
但是如果我们使用mod,会发生奇怪的事(mod -4 3) => 2:

  • 3小于-4的最大整数倍数为-6.
  • -4减-6是2.

因此即使它们通常表现相似,mod也不会返回余数,它会做更具体的事情.

您可能会发现这些clojuredocs示例很有帮助.