我可以依靠C中的%(模)运算符获得负数吗? [英] Can I rely on % (modulo) operator in C for negative numbers?
问题描述
使用GCC:
printf("%i \n", -1 % (int)4);
printf("%u \n", -1 % (unsigned int)4);
输出:
-1
3
我可以跨平台依赖此行为吗?我是否应该明确定义 MOD
和 REM
宏,以确保这没有改变?
Can I rely on this behaviour across platforms? Should I explicitly define MOD
and REM
macros to be sure this isn't altered?
推荐答案
从C99开始,%的结果要求 四舍五入到 ,如Chris Dodd所引用.
From C99 onwards the result of %
is required to be rounded toward 0 as quoted by Chris Dodd.
在C99标准之前,%
运算符对负数的行为是定义的实现.
Prior to C99 standard, %
operator's behavior on negative number is implementation defined.
当整数相除且除法不精确时,如果两个操作数均为正,则
/
运算符的结果是小于代数商和%<的结果的最大整数/code>运算符为正.如果任一操作数为负,则实现是
/
运算符的结果是小于代数商的最大整数还是大于代数商的最小整数定义,以及%
运算符结果的符号.如果商a/b
是可表示的,则表达式(a/b)* b + a%b
应等于a
.
When integers are divided and the division is inexact, if both operands are positive the result of the
/
operator is the largest integer less than the algebraic quotient and the result of the%
operator is positive. If either operand is negative, whether the result of the/
operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the%
operator. If the quotienta/b
is representable, the expression(a/b)*b + a%b
shall equala
.
因此,如果您定位的是C99或更高版本,则结果为是.否则,您将不能依靠它.
So the result is Yes if you're targeting C99 or newer, otherwise you can't rely on that.
如果您需要一致的结果以及可移植到甚至更老的C标准的结果,则可以使用 div
或 ldiv
,无需定义自己的 MOD
和 REM
If you need consistent result with portability to even older C standards, you can use div
or ldiv
, no need to define your own MOD
and REM
因为当涉及到负操作数时,C89具有实现定义的有符号整数的划分语义,因此发明了div和ldiv以及C99中的lldiv来为有符号的整数除法和余数运算提供明确指定的语义.
Because C89 had implementation-defined semantics for division of signed integers when negative operands were involved, div and ldiv, and lldiv in C99, were invented to provide well-specified semantics for signed integer division and remainder operations.
这篇关于我可以依靠C中的%(模)运算符获得负数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!