c语言中7%3是什么意思,为什么7%(-4)的结果是3?

本文详细解读了C++11中关于取余运算符(%)的最新规定,包括整型要求、正负余数处理、行为一致性与早期版本的区别,以及具体运算规则如m%(-n)等于m%n。重点讲解了7%-4等同于7%4这一示例。

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

新的C++11标准对取余有了比较明确的规定:

C++ Primer 5th:

The % operator, known as the “remainder” or the “modulus” operator, computes the remainder that results from dividing the left-hand operand by the right-hand operand. The operands to % must have integral type.

In a division, a nonzero quotient is positive if the operands have the same sign and negative otherwise. Earlier versions of the language permitted a negative quotient to be rounded up or down; the new standard requires the quotient to be rounded toward zero (i.e., truncated).

The modulus operator is defined so that if m and n are integers and n is nonzero, then (m/n)*n + m%n is equal to m. By implication, if m%n is nonzero, it has the same sign as m. Earlier versions of the language permitted m%n to have the same sign as n on implementations in which negative m/n was rounded away from zero, but such implementations are now prohibited. Moreover, except for the obscure case where -m overflows, (-m)/n and m/(-n) are always equal to -(m/n), m%(-n) is equal to m%n,

and (-m)%n is equal to -(m%n). More concretely:

m%(-n) is equal to m%n,所以7%-4等同于7%4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值