Modulo operation with negative numbers

前端 未结 12 1439
旧巷少年郎
旧巷少年郎 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:44

    Modulus operator gives the remainder. Modulus operator in c usually takes the sign of the numerator

    1. x = 5 % (-3) - here numerator is positive hence it results in 2
    2. y = (-5) % (3) - here numerator is negative hence it results -2
    3. z = (-5) % (-3) - here numerator is negative hence it results -2

    Also modulus(remainder) operator can only be used with integer type and cannot be used with floating point.

提交回复
热议问题