Modulo operation in C for -ve values

Deepak Gaur dgaur at cdotd.ernet.in
Mon Nov 12 22:55:33 EST 2007


The Modulo operation as specified in
http://xenia.media.mit.edu/~bdenckla/thesis/texts/htthe/node13.html says that
for a fraction like n/k which can be expressed as n/k = i + j/k the C division
and mod operation should yeild
n div k = i (integer part)
n mod k = j (remainder part)
For n +ve above is true
For n -ve
-n/k = -i + j/k
-n div k = -i
-n mod k = j (+ve remainder)

But running a sample program on Redhat enterprise Linux EL4
with libc-2.3.4 gcc version 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n,k,j;
n=-3;
k=8;
j=(n/k);
printf("\n n div k %d", j);
j=(n%k);
printf("\n n mod k %d", j);
}
gives following output for n = -3 k = 8
n div k 0
n mod k  -3
though it should have been as per hypothesis proposed in
http://xenia.media.mit.edu/~bdenckla/thesis/texts/htthe/node13.html
n div k -1
n mod k  5

Which is correct(0,-3) or (-1,5)? 

Thanks
Deepak Gaur


More information about the Linuxppc-embedded mailing list