quotRem 和 divMod 的区别什么时候有用? [英] When is the difference between quotRem and divMod useful?
问题描述
来自haskell报告:
From the haskell report:
quot、rem、div 和 mod 类如果 y 是,则方法满足这些定律非零:
The quot, rem, div, and mod class methods satisfy these laws if y is non-zero:
(x `quot` y)*y + (x `rem` y) == x
(x `div` y)*y + (x `mod` y) == x
quot
是整数除法被截断趋向于零,而 div
的结果向负无穷大截断.
quot
is integer division truncated
toward zero, while the result of div
is truncated toward negative infinity.
例如:
Prelude> (-12) `quot` 5
-2
Prelude> (-12) `div` 5
-3
有哪些示例可以说明结果截断方式之间的差异很重要?
What are some examples of where the difference between how the result is truncated matters?
推荐答案
许多语言都有一个mod"或%"运算符,它给出除法后的余数,并截断到 0;例如 C、C++ 和 Java,可能还有 C#,会说:
Many languages have a "mod" or "%" operator that gives the remainder after division with truncation towards 0; for example C, C++, and Java, and probably C#, would say:
(-11)/5 = -2
(-11)%5 = -1
5*((-11)/5) + (-11)%5 = 5*(-2) + (-1) = -11.
Haskell 的 quot
和 rem
旨在模仿这种行为.我可以想象在某些人为的情况下可能需要与某些 C 程序的输出兼容.
Haskell's quot
and rem
are intended to imitate this behaviour. I can imagine compatibility with the output of some C program might be desirable in some contrived situation.
Haskell 的 div
和 mod
,以及随后的 Python 的/和 %,遵循数学家(至少是数论学家)的惯例,总是将 向下截断em> 除法(不向 0 - 向负无穷大),以便余数始终为非负.因此在 Python 中,
Haskell's div
and mod
, and subsequently Python's / and %, follow the convention of mathematicians (at least number-theorists) in always truncating down division (not towards 0 -- towards negative infinity) so that the remainder is always nonnegative. Thus in Python,
(-11)/5 = -3
(-11)%5 = 4
5*((-11)/5) + (-11)%5 = 5*(-3) + 4 = -11.
Haskell 的 div
和 mod
遵循这种行为.
Haskell's div
and mod
follow this behaviour.
这篇关于quotRem 和 divMod 的区别什么时候有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!