Modulo operation with negative numbers

In ac program i was trying the below operations(Just to check the behavior )

 x = 5 % (-3);
 y = (-5) % (3);
 z = (-5) % (-3); 

printf("%d ,%d ,%d", x, y, z); 

gave me output as (2, -2 , -2) in gcc . I was expecting a positive result every time. Can a modulus be negative? Can anybody explain this behavior?


C99 requires that when a/b is representable:

(a/b) * b + a%b shall equal a

This makes sense, logically. Right?

Let's see what this leads to:


Example A. 5/(-3) is -1

=> (-1) * (-3) + 5%(-3) = 5

This can only happen if 5%(-3) is 2.


Example B. (-5)/3 is -1

=> (-1) * 3 + (-5)%3 = -5

This can only happen if (-5)%3 is -2


The % operator in C is not the modulo operator but the remainder operator.

Modulo and remainder operators differ with respect to negative values.

With a remainder operator, the sign of the result is the same as the sign of the dividend while with a modulo operator the sign of the result is the same as the divisor.

C defines the % operation for a % b as:

  a == (a / b * b) + a % b

with / the integer division with truncation towards 0 . That's the truncation that is done towards 0 (and not towards negative inifinity) that defines the % as a remainder operator rather than a modulo operator.


Based on the C99 Specification: a = (a / b) * b + a % b

We can write a function to calculate (a % b) = a - (a / b) * b !

int remainder(int a, int b)
{
    return a - (a / b) * b;
}

For modulo operation, we can have the following function (assuming b>0)

int mod(int a, int b)
{
    int r = a % b;
    return r < 0 ? r + b : r;
}

My conclusion is (a % b) in C is a remainder operator and NOT modulo operator.

链接地址: http://www.djcxy.com/p/58288.html

上一篇: 使用Modulo来计算余数

下一篇: 模数运算与负数