Mod negative numbers in C

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 way out

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

But according to this calculator mod -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 happens in C that produces -2 instead of 8?

+3
source share
3 answers

The C11 standard says:

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

with footnote 105:

105) This is often called "truncation to zero."

-. . Python, , , user3307862 .

%, "", , [0..b), (-b..b) /.

+4

modulo 10, -2 8. .

+1

C . .

Python:

python

0

All Articles