cmathgcccygwinmodulo

fmod function from math.h library in C not working correctly?


Ok, so hopefully I do not look like an idiot from asking this question...as it is quite basic, but my brain is either on vacation or something is indeed wrong.

So -4 % 5 or -4 mod 5 should equal 1 correct? Why is it that the fmod function from the math.h library returns -4 when you use it, i.e fmod(-4, 5) returns -4 instead of 1. I'm using the gcc compiler via cygqin if that is any help as well.

Thanks!


Solution

  • The % operator is the remainder operator, not modulo. The fmod function is also the floating point remainder, not modulo. In this case, they have selected to round -4/5 toward 0 to an integer.