gpt4 book ai didi

c++ - 具有负值的模运算符

转载 作者:行者123 更新时间:2023-11-30 16:42:12 31 4
gpt4 key购买 nike

为什么要进行这样的操作:

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 % operatoryields the remainder from the division of the first expression by thesecond. If the second operand of / or % is zero the behavior isundefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b isrepresentable 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; ifnot, the sign of the remainder is implementation-defined.

ISO14882:2003(e) 中的内容不再出现在 ISO14882:2011(e) 中

关于c++ - 具有负值的模运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45925243/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com