Home > Enterprise >  In Java why does 3 / 2.0 = 1.5 but 3 % 2.0 = 1.0?
In Java why does 3 / 2.0 = 1.5 but 3 % 2.0 = 1.0?

Time:04-01

System.out.println(3/2.0);
System.out.println(3%2.0);

Output:
1.5
1.0 (*)

(*) Why 1.0 why not 0 since 2 * 1.5 = 3 ?

CodePudding user response:

This tutorial on the % operator explains it rather well:

... how many times does 2.5 go into 7.5 and what's leftover? The answer is that 2.5 goes into 7.5 three times with zero leftovers, and it's that zero which is the result of 7.5 % 2.5 in Java.

If we now use your values, 3 and 2.0, then the question is

How many times does 2.0 go in 3, and what's the leftvoer?

And the answer is that 2.0 goes one time in 3, with 1.0 as the leftover.

For floating point values, the modulo operator gives you the leftover part.

CodePudding user response:

there is a different between % and /, the % operator returns the rest of the division.i this case 3%2=1 because 3=2 1,i another way you want to figure out how many 2's in this 3. and the / operator is the normal division

  •  Tags:  
  • java
  • Related