cmodulo

Why can't you check if a negative number is odd by comparing the remainder of division by 2 with 1?


When i compare remainder with 1, it doesn't work as i expect:

int t = (-3 % 2) == 1; printf("is odd: %d\n", t);

result is: 0

When i compare with 0:

int t = (-3 % 2) != 0

then it works.

Can you explain why?


Solution

  • Look at the output of the following small program, this will answer your question.

    int main()
    {
      printf(" 3%%2 = %d\n", 3%2);
      printf("-3%%2 = %d\n", -3%2);
    }
    

    Output:

     3%2 = 1 
    -3%2 = -1