Modulo operation with negative numbers

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

    I believe it's more useful to think of mod as it's defined in abstract arithmetic; not as an operation, but as a whole different class of arithmetic, with different elements, and different operators. That means addition in mod 3 is not the same as the "normal" addition; that is; integer addition.

    So when you do:

    5 % -3
    

    You are trying to map the integer 5 to an element in the set of mod -3. These are the elements of mod -3:

    { 0, -2, -1 }
    

    So:

    0 => 0, 1 => -2, 2 => -1, 3 => 0, 4 => -2, 5 => -1
    

    Say you have to stay up for some reason 30 hours, how many hours will you have left of that day? 30 mod -24.

    But what C implements is not mod, it's a remainder. Anyway, the point is that it does make sense to return negatives.

提交回复
热议问题