C++ 具有负值的模运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7594508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:12:01  来源:igfitidea点击:

Modulo operator with negative values

c++

提问by scdmb

Why do such operations:

为什么要做这样的操作:

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

give different results?

给出不同的结果?

-1
1

回答by PlasmaHH

From ISO14882:2011(e) 5.6-4:

来自 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.

二元 / 运算符产生商,二元 % 运算符产生第一个表达式除以第二个表达式的余数。如果 / 或 % 的第二个操作数为零,则行为未定义。对于整数操作数, / 运算符产生代数商,其中任何小数部分都被丢弃;如果商 a/b 在结果的类型中是可表示的,则 (a/b)*b + a%b 等于 a。

The rest is basic math:

剩下的是基础数学:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

Note that

注意

If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

如果两个操作数都为非负,则余数为非负;如果不是,余数的符号是​​实现定义的。

from ISO14882:2003(e) is no longer present in ISO14882:2011(e)

来自 ISO14882:2003(e) 不再出现在 ISO14882:2011(e) 中

回答by Kto To

a % b

in c++ default:

在 C++ 中默认:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

在蟒蛇中:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

在 C++ 到 python:

(b + (a%b)) % b

回答by Nawaz

The signin such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),

在这种情况下(即当一个或两个操作数为负时)的符号是实现定义的。规范在 §5.6/4 (C++03) 中说,

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; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

二元 / 运算符产生商,二元 % 运算符产生第一个表达式除以第二个表达式的余数。如果 / 或 % 的第二个操作数为零,则行为未定义;否则 (a/b)*b + a%b 等于 a。如果两个操作数都为非负,则余数为非负;如果不是,则余数的符号是​​ implementation-defined

That is all the language has to say, as far as C++03 is concerned.

就 C++03 而言,这就是语言要说的全部内容。