简体   繁体   English

C++ 中的除法运算符 ( / ) 是否在 num 具有相同符号和 ceil 值的情况下返回 floor 值,当两个数字具有相反的符号时?

[英]Does division operator ( / ) in C++ return the floor value in case of num with same sign and ceil value when both the numbers are of opposite sign?

In C++, when both numerator and denominator are integers and of same sign, then division operator gives the floor value of the quotient.在C++中,当分子和分母均为整数且符号相同时,除法运算给出商的底值。 But when they are of opposite sign, then it gives ceil value.但是当它们的符号相反时,它就会给出 ceil 值。 Is my understanding correct or is there more to it?我的理解是正确的还是还有更多?

You have it right.你说得对。 Some 20th-century hardware engineer decided to do it this way, and as far as I know this is how all microprocessors now natively do it.一些 20 世纪的硬件工程师决定这样做,据我所知,现在所有的微处理器都是这样做的。 Mathematically, it's often a little inconvenient, which is why Python (for example) corrects in software always to round toward toward floor.从数学上讲,这通常有点不方便,这就是为什么 Python(例如)在软件中更正总是朝着地板方向舍入。

For additional insight, besides p/q for an integer quotient, try p%q for the corresponding remainder.要获得更多见解,除了 integer 商的p/q之外,请尝试p%q相应的余数。

Your question is tagged C++ but this is really a computer hardware issue and, as such, it may be more helpful to consult the C17 standard, whose sect.你的问题被标记为C++但这实际上是一个计算机硬件问题,因此,查阅 C17 标准可能更有帮助,其 sect. 6.5.5(6) reads: 6.5.5(6) 内容如下:

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.当整数相除时, /运算符的结果是舍去任何小数部分的代数商。 If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a ....如果商a/b是可表示的,则表达式(a/b)*b + a%b应等于a ....

(I have a shred of a memory from 25 or 30 years ago, reading about a CPU that rounded toward floor. If my memory is not altogether imaginary, then that CPU apparently did not succeed in the marketplace, did it?) (我有一个 memory 的碎片,来自 25 或 30 年前,读到一个 CPU 向地板四舍五入。如果我的 memory 不是完全虚构的,那么那个 CPU 显然没有在市场上取得成功,不是吗?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM