Question

In C the following code ...

#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;
}

gives this output

> gcc modTest.c
> ./a.out
-12 mod 10 = -2

But according to this mod calculator -12 mod 10 = 8

In 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

What is going on in C that produces -2 instead of 8?

Était-ce utile?

La solution

The C11 standard says:

6.5.5:6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.(105) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined.

with footnote 105:

105) This is often called ‘‘truncation toward zero’’.

Another way to define division is to round towards -oo. This is called Euclidean division. Python appears to use yet another definition, according to user3307862's link.

The % operator, properly called “remainder”, is defined with respect to the corresponding division, so it either is always in [0..b) or in (-b..b) depending on the definition of /.

Autres conseils

In modulo 10, -2 is equivalent to 8. They're just two different representations of the same thing.

C is doing correct math. You can check it on the regular calculator.

Python behavior is explained here:

negative numbers modulo in python

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top