Modulo operation with negative numbers

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

    The result of Modulo operation depends on the sign of numerator, and thus you're getting -2 for y and z

    Here's the reference

    http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_14.html

    Integer Division

    This section describes functions for performing integer division. These functions are redundant in the GNU C library, since in GNU C the '/' operator always rounds towards zero. But in other C implementations, '/' may round differently with negative arguments. div and ldiv are useful because they specify how to round the quotient: towards zero. The remainder has the same sign as the numerator.

提交回复
热议问题