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
is 0.3590664272890485
I noticed that if i cast a
and b
to double
in the division line
double divisionResult = (double) a / (double) b;
It works perfectly.
Why do i have to cast my variables to double to get the real division result?
The result of dividing a double by a double is a double. However, if both expressions have type int, then the result is an int.
Integer division determines how many times one integer goes into another. The remainder after integer division is simply dropped, no matter how big it is. because 4 goes into 7 just once. The result is not rounded up to 2.
When dividing an integer by an integer, the answer will be an integer (not rounded). When an operation involves two types (as the mixed division shown above), the smaller type is converted to the larger type. In the case above, the integer 5 was converted to a double type before the division occurred.
If both operands are integers, C++ performs integer division. That means any fractional part of the answer is discarded, making the result an integer. If one or both operands are floating-point values, the fractional part is kept, making the result floating-point.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With