gcc-模运算错误的结果

时间:2019-05-22 21:49:28

标签: c gcc modulo integer-division

在调试我的C代码时,我注意到模运算符不能计算正确的结果。我已将代码分成一个文件,但没有成功...这里发生了什么?

我的系统:

$ cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core)
$ uname -s -r
Linux 3.10.0-957.12.2.el7.x86_64
$ uname -v
#1 SMP Tue May 14 21:24:32 UTC 2019
$ gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-36)
#include <stdio.h>
int main() {
    int i;
    printf("[");
    for(i=-11; i<=11; i++) {
        printf("%d ", i%11);
    }
    printf("]\n");
    return 0;
}

编译并运行:

gcc -Wall -Wextra -o test_modulo test_modulo.c
./test_modulo
[0 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 0 ]

python-console中的模函数:

>>> print([i % 11 for i in range(-11,11)])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

0 个答案:

没有答案