Modulo operation with negative numbers

前端 未结 12 1624
旧巷少年郎
旧巷少年郎 2020-11-22 06:10

In a C 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         


        
12条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 06:48

    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 that a % b in C is a remainder operation and NOT a modulo operation.

提交回复
热议问题