具有负值的模运算符 [英] Modulo operator with negative values
问题描述
为什么要这样操作:
std::cout << (-7 % 3) << std::endl;
std::cout << (7 % -3) << std::endl;
给出不同的结果?
-1
1
推荐答案
从ISO14882:2011(e)5.6-4:
From ISO14882:2011(e) 5.6-4:
二进制/运算符产生商,二进制%operator
产生第一个表达式除以
秒的余数。如果/或%的第二个操作数为零,则行为是
未定义。对于积分操作数,/运算符产生代数商,其中丢弃任何小数部分;如果商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.
其余的基本数学:
(-7/3) => -2
-2 * 3 => -6
so a%b => -1
(7/-3) => -2
-2 * -3 => 6
so a%b => 1
请注意
如果两个操作数都是非负的,则余数是非负的;如果
不,则余数的符号是实现定义的。
If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
来自ISO14882:2003存在于ISO14882:2011(e)
from ISO14882:2003(e) is no longer present in ISO14882:2011(e)
这篇关于具有负值的模运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!