Unexpected result while dividing int by int and storing result into double
Solution 1
Because in integer division, if the answer is not a perfect integer, the digits after the decimal point will be removed (integer division yields integer value).
Note that you don't have to cast the both integers, you can cast only one, the second will be implicitly converted.
Why after the cast it works?
Because cast has higher precedence than /
. So first it cast, then it divides. If this were not the case, you would get 0.0
.
Solution 2
As always, any calculation on the right side of the assignment operator is executed before assigning its result to the variable specified on the left side. When the calculation is performed, it is a division between two int
s, which is an integer division, which (as I'm sure you know), produces an integer result (i.e. a quotient without any remainder). Only after this calculation is performed is the result of the integer division - which is 0 - cast to a double.
As you observed, changing one or both of the int
s to a double makes the calculation a double division, rather than an integer division.
Solution 3
a is int, and b is int, dividing a/b results an int value so 0.35 converted to int becomes 0.So you have to cast it like
double d = (double)a/b;
Comments
-
BackSlash over 1 year
I'm having a weird problem.
This code simply divides an int by another int, stores result in a double variable and prints it:
int a = 200; int b = 557; double divisionResult = a / b; System.out.println("Result: " + divisionResult);
After executing this code, the output is:
Result: 0
This is weird, because
200/557
is0.3590664272890485
I noticed that if i cast
a
andb
todouble
in the division linedouble divisionResult = (double) a / (double) b;
It works perfectly.
Why do i have to cast my variables to double to get the real division result?
-
zakinster about 11 yearsNote that this only works because the
cast operator
has a higher precedence than thedivision operator
, which is not obvious at first sight. -
zakinster about 11 yearsEven if the
cast
had a lower precedence than/
, the OP's division would still work since the right operand would be casted anyway.