Pregunta

I am running a for loop and inside my loop I have the following:

for(int i = 0; i < 12; i = i + 2){
        System.out.println("i = " + i);
        System.out.print("3 - i % 3 (i is at " + i + ") = " + (3 - i % 3));
        System.out.println();
        System.out.println("3 - i (" + (i) + ") = " + (3 - i));
    }

I do understand how Modulus works normally or with positive numbers, but I do not understand how it works with negative integers? Can anyone explain it to me please?

Many thanks.

¿Fue útil?

Solución 2

 4 %  3 ==  1
-4 %  3 == -1
 4 % -3 ==  1
-4 % -3 == -1

Changing the sign of the first number changes the sign of the result. The sign of the second number doesn't matter.

This is true in many languages (C, C++, Java, Javascript) but not all languages (Python, Ruby).

Otros consejos

a mod b is very well defined for positive integers a and b. What if a or b are negative? There are three choices that are consistent with that base definition:

  1. a mod b is always positive.
  2. a mod b has the same sign as a.
  3. a mod b has the same sign as b.

Different languages will choose one of these three choices. There is no singular correct answer.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top