我似乎记得 ANSI C 没有指定当模运算符的任一操作数为负时应该返回什么值(只是它应该是一致的)。是后来指定的,还是一直指定的,我记错了?
最佳答案
C89,不完全 (§3.3.5/6)。它可以是 -5 或 5,因为 -5/10 可以返回 0 或 -1(%
是根据涉及 /
的线性方程定义的, *
和 +
):
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,是的(§6.5.5/6),结果必须是-5:
When integers are divided, the result of the
/
operator is the algebraic quotient with any fractional part discarded.88) If the quotienta/b
is representable, the expression(a/b)*b + a%b
shall equala
.88) This is often called "truncation toward zero".
类似地,在 C++98 中,结果是实现定义的(§5.6/4),遵循 C89 的定义,但提到首选向零舍入规则,
... If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined74).
74) According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.
事实上它成为了 C++0x 中的标准规则 (§5.6/4):
... For integral operands the
/
operator yields the algebraic quotient with any fractional part discarded;82 ...82) This is often called truncation towards zero.
关于c - ANSI C 或 ISO C 是否指定 -5 % 10 应该是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3609572/