您的位置:首页 > 编程语言 > C语言/C++

c及c++中的取模运算

2015-06-18 22:34 567 查看
首先看C++中两个涉及到模运算的操作:

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


上述两个操作的结果分别为-1和1。为何会这样呢?

首先引述下2011年的ISO标准:

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


注意标准ISO14882:2003(e)中的如下叙述并没有继续在标准ISO14882:2011(e)中出现,换句话说在新标准中除法运算以及取模运算的结果都是确定的,不再是由某个实现来定义。

If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: