2

I have the following code snippet:

#include <stdio.h>

int main(){
    printf("%d\r\n", -1 % 7);
    return 0;
}

When run, it prints -1. According to my own math and calculators like this one (http://www.miniwebtool.com/modulo-calculator/?number1=-1&number2=7), my answer should be 6. Im assuming there is some 'gotcha' in the C implementation of modulo that I am not grasping. Can someone explain why I am not getting the answer I expect?

mstagg
  • 507
  • 4
  • 16

1 Answers1

0

The rule of C (after C99) is that the sign of the result of i%j is same as the sign of i. The answer you are getting is correct.

In C89 the result of i%j (if either i or j is negative) depends on the implementation. -1%7 could either be -1 or 6.

haccks
  • 104,019
  • 25
  • 176
  • 264