c – 具有负值的模运算符

参见英文答案 > Why does C++ output negative numbers when using modulo?                                    3个
为什么这样的操作:

std::cout << (-7 % 3) << std::endl;
std::cout << (7 % -3) << std::endl;

给出不同的结果?

-1
1
最佳答案
来自ISO14882:2011(e)5.6-4:

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(e)中不再出现ISO14882:2011(e)

转载注明原文:c – 具有负值的模运算符 - 代码日志