quotRem 和 divMod 的区别什么时候有用? [英] When is the difference between quotRem and divMod useful?

查看:32
本文介绍了quotRem 和 divMod 的区别什么时候有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自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 的 quotrem 旨在模仿这种行为.我可以想象在某些人为的情况下可能需要与某些 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 的 divmod,以及随后的 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 的 divmod 遵循这种行为.

Haskell's div and mod follow this behaviour.

这篇关于quotRem 和 divMod 的区别什么时候有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆