Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The sign of the modulo operator result? [duplicate]

Tags:

c

modulo

I have couple line of C code testing the modulo operator as follows:

// line 1
printf("%d\n", 5 % (-3)); => output: 2
// line 2
printf("%d\n", -5 % 3); => output: -2

I know that the sign of the modulo depends on the sign of the numerator, but I am curious why not otherwise?

like image 373
ipkiss Avatar asked Oct 23 '22 10:10

ipkiss


1 Answers

5/(-3) = -1;
(-5)/3 = -1; 

If that is agreed then let's calculate the remainder

Remainder = Dividend - ( Divisor * Factor)

5 - (-3 * -1) = 2
-5 - (3 * -1) = -2 
like image 73
Pushparaj Avatar answered Oct 31 '22 13:10

Pushparaj