SA6*_*610 5 c negative-number modulus
在 C 语言中,以下代码...
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<stdlib.h>
int main() {
int result = (-12) % (10);
printf("-12 mod 10 = %d\n",result);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
给出这个输出
> gcc modTest.c
> ./a.out
-12 mod 10 = -2
Run Code Online (Sandbox Code Playgroud)
但根据这个 mod 计算器-12 mod 10 = 8
在Python中...
> python
Python 3.3.0 (default, Mar 26 2013, 09:56:30)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> (-12) % (10)
8
Run Code Online (Sandbox Code Playgroud)
C 中发生了什么,产生 -2 而不是 8?
C11标准说:
\n\n\n\n\n6.5.5:6 整数相除时,/运算符的结果是舍去小数部分的代数商。(105) 如果商 a/b 可表示,则表达式 (a/b)*b + a% b 应等于 a;否则,a/b 和 a%b 的行为都是未定义的。
\n
附注105:
\n\n\n\n\n105) 这通常称为\xe2\x80\x98\xe2\x80\x98朝零\xe2\x80\x99\xe2\x80\x99截断。
\n
定义除法的另一种方法是向 -oo 舍入。这称为欧几里得除法。根据 user3307862 的链接,Python 似乎使用了另一个定义。
\n\n运算%符,正确地称为 \xe2\x80\x9cremainder\xe2\x80\x9d,是根据相应的除法定义的,因此它要么总是在 [0..b) 中,要么总是在 (-b..b) 中,具体取决于的定义/。