Clojure中mod和rem的区别

时间:2016-05-13 13:12:02

标签: clojure clojurescript

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

2 个答案:

答案 0 :(得分:12)

mod返回第一个数字的差值,以及小于第一个数字的第二个数字的最大整数(可能是负数)倍数:
rem只是其余部分。

例如(rem -4 3) => -1这里不出意外:-4除以3是-1,其中-1“留下” 但是如果我们使用mod:(mod -4 3) => 2

,就会发生奇怪
  • 小于-4的3的最大整数倍是-6。
  • -4减-6是2。

所以尽管他们通常表现相似,但是会返回余数,它会做更具体的事情。

You might find these clojuredocs examples helpful.

答案 1 :(得分:10)

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