0
    private int mCurrentIndex = 0;
    mPrevButton = (Button)findViewById(R.id.prev_button);
    mPrevButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mCurrentIndex = (-33 % 5);
            Log.i("IndexClick", String.valueOf(mCurrentIndex));
        }
    });

This is returning -3 instead of a 2. It does the math right with a positive number. Please help can't seem to find a solution.

2 Answers2

4

With the % operator, the sign of the remainder must match the sign of the dividend (or be 0), according to the JLS, Section 15.17.3:

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.

It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.

And in fact, (-33/5)*5 + (-33%5) becomes -6*5 + (-3) which equals -33.

To get a positive result, you must have a positive dividend.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 1
    +1 for JLS. Also to get `2` instead of `-3` OP can add 5 to result and in case new result will not be negative use modulo 5 again like `(-33 % 5 + 5) %5` – Pshemo Dec 19 '13 at 18:37
0

According to the JLS:

The remainder operation for operands that are integer ... produces a result value such that (a/b)*b+(a%b) is equal to a.

In your example, a = -33 and b = 5. Therefore:

(a/b)*b+(a%b) = -33
(-33/5)*5+(-33%5) = -33
(-6)*5+(-33%5) = -33
-30+(-33%5) = -33
(-33%5) = -3, as expected
asaini007
  • 858
  • 5
  • 19