user3423927 - 11 months ago 91

Java Question

this is my program. And it is printing 10. I don't know why. Any help would be appreciated.

`public static void main(String[] args) {`

double a=10;

double b=20;

System.out.println(a % b);

}

I am expecting 0 as reminder as 20 goes to 10 with 0.5 times leaving 0 as reminder.

Answer

`%`

is called the modulous (modulo or mod) operator. It means to take the remainder (or amount left over) of an integer division.

For example, `10 / 20`

doesn't result in a whole number in integer division (it results in`.5`

), and leaves a remainder. That remainder is `10`

.

Here are some examples (all division is integer division)

```
10 / 20 = 0, remainder 10. Thus, 10 % 20 = 10
3 / 2 = 1, remainder 1. So, 3 % 2 = 1
4 / 2 = 2, remainder 0. and 4 % 2 = 0
```

EDIT:

Since `a`

and `b`

are doubles, it's possible that you are trying to use mod with doubles. In that case I would take a look at How do I use modulus for float/double? However, note that even when `a`

and `b`

are explicitly written as doubles (`10.0`

and `20.0`

), the result of the modulo is still `10.0`

. The explanation for why this isn't `.5`

is given pretty clearly in this answer, which cites the JLS rules for IEEE arithmetic (and is reiterated in Stephen C's answer).