C ++运算符%保证 [英] C++ operator % guarantees
问题描述
是否保证( - x)%m
,其中 x
和 m c> - (x%m)
是正的,在c ++ 标准(c ++ 0x)
Is it guaranteed that (-x) % m
, where x
and m
are positive in c++ standard (c++0x) is negative and equals to -(x % m)
?
我知道在我所知道的所有机器上都是正确的。
I know it's right on all machines I know.
推荐答案
除了 Luchian 的答案,这是C ++ 11标准的相应部分:
In addition to Luchian's answer, this is the corresponding part from the C++11 standard:
二元的/运算符产生商,二元的%运算符
产生第一个表达式除以
秒的余数。如果/或%的第二个操作数为零,则行为是
未定义。对于积分操作数,/运算符产生代数
商,其中丢弃任何小数部分;如果商a / b是在结果类型中表示的
,(a / b)* b + a%b等于a。
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.
这错过了最后一句话。所以部分
Which misses the last sentence. So the part
(a / b)* b + a%b等于
(a/b)*b + a%b is equal to a
是唯一依赖的引用,这意味着 a%b
将始终具有 a
,因为 /
的截断行为。所以如果你的实现在这方面遵守C ++ 11标准,模运算的符号和值的确完美地定义为负操作数。
Is the only reference to rely on, and that implies that a % b
will always have the sign of a
, given the truncating behaviour of /
. So if your implementation adheres to the C++11 standard in this regard, the sign and value of a modulo operation is indeed perfectly defined for negative operands.
这篇关于C ++运算符%保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!