c - ANSI C 或 ISO C 是否指定 -5 % 10 应该是多少?

标签 c c99 modulo c89

我似乎记得 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 quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

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 quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

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/

相关文章:

c - gdb 通过指向错误的代码行显示不正确的回溯

c - R_X86_64_32S 和 R_X86_64_64 重定位是什么意思?

c - C99中局部静态数组的线程安全

c++ - 关于 C++ 中 % 运算符的问题

Swift - 查找是所有数字 1...20 的倍数的数字

javascript - Javascript 中大量数字的模运算符不准确

C型带功能开关盒

c - 是/否提示重新运行程序

c++ - 使用新标准

c - 如何将字符串文字与 4 的倍数的地址对齐?