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?

3
  • 2
    Read stackoverflow.com/questions/11720656/… Commented Dec 21, 2015 at 16:33
  • FWW: -1 % 7 also returns -1 in JavaScript, but it does return 6 in Python. Commented Dec 21, 2015 at 16:36
  • So what do I need to do to get the expected behavior? Commented Dec 21, 2015 at 16:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.