c及c++中的取模运算

本文详细解析了C++中模运算的操作及ISO标准中的规定,通过实例展示了(-7%3)和(7%-3)的结果,并对比了不同版本标准中关于模运算的解释,帮助理解C++模运算的原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先看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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值