[英]C++ operator % guarantees
Is it guaranteed that (-x) % m
, where x
and m
are positive in c++ standard (c++0x) is negative and equals to -(x % m)
? 是否保证
(-x) % m
,其中x
和m
在c ++ 标准中是正的(c ++ 0x)是负的并且等于-(x % m)
?
I know it's right on all machines I know. 我知道它在我知道的所有机器上都是正确的。
In addition to Luchian 's answer, this is the corresponding part from the C++11 standard: 除了Luchian的回答,这是C ++ 11标准的相应部分:
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.
如果商a / b在结果的类型中是可表示的,则(a / b)* b + a%b等于a。
Which misses the last sentence. 哪个错过了最后一句话。 So the part
所以这部分
(a/b)*b + a%b is equal to a
(a / b)* b + a%b等于a
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 /
. 是依靠唯一的参考,而且意味着
a % b
将始终具有的符号a
,鉴于截断行为/
。 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 ++ 11标准,那么模运算的符号和值确实是为负操作数完美定义的。
4) The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second.
4)二进制/运算符产生商,二元%运算符从第一个表达式除以第二个表达式得到余数。 If the second operand of / or % is zero the behavior is undefined;
如果/或%的第二个操作数为零,则行为未定义; otherwise (a/b)*b + a%b is equal to a.
否则(a / b)* b + a%b等于a。 If both operands are nonnegative then the remainder is nonnegative;
如果两个操作数都是非负的,那么余数是非负的; if not, the sign of the remainder is implementation-defined (emphasis mine)
如果没有,余数的符号是实现定义的 (强调我的)
This is from C++03 though. 这是来自C ++ 03。 :(
:(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.