So I have this code:
int x = 435;
int y = x / 2 * 5;
If I calculate y by hand, I get a result of 1087.5. But when I print the integer y out, I get the result 1085. Why is this? Shouldn't it round to either 1088 or 1087?
So I have this code:
int x = 435;
int y = x / 2 * 5;
If I calculate y by hand, I get a result of 1087.5. But when I print the integer y out, I get the result 1085. Why is this? Shouldn't it round to either 1088 or 1087?
It's because of integer arithmetic:
int/int = int
So, 435/2
will be
435/2 = 217
And
217*5 = 1085
What can you do? Cast the values as you need:
int y = (int)((float)x / 2 * 5);
or if you want a real result, declare the variable y
as float
:
float y = (float)x / 2 * 5;
this saves in result of each part as an int
so
435 / 2 == 217
217 * 5 == 1085
int
value of x/2=217
and 217 * 5 == 1085
is the reason
you are dividing int
value x
so result will be int
value (int/int=int)
x/2=217
Then
217*5=1085
Try this:
int x = 435;
double y = ((double) x / 2) * 5;
y
cannot be int (or else you will lose precision). Moreover, x / 2
will yield you an integer
value, hence you need to cast it to double
or float
Java is using integer math, this
int x = 435;
int y = x / 2 * 5;
is equivalent to
int x = 435;
int y = x / 2; // <-- 217
y *= 5; // <-- 1085
If you wanted to round the other way try,
int x = 435;
int y = (int) Math.round(((double) x / 2) * 5); // <-- 1088
When you divide 435 by 2. It stores 217 not 217.5 and hence after multiplying 217*5= 1085
You are trying to store a float value into INT and hence getting the truncated value.
Also,without brackets, the compiler will start to execute from LHS to RHS one by one according to priority of operator.
Your code
int x = 435; int y = x / 2 * 5;
is actually performing the following operation.
Using int will truncate 217.5 into 217 and hence you are getting that answer. Use double or float for storing the kind of answer you want
int x = 435; double y = y=(x/2)*5
This will get you the required answer.
the answer is correct as -: 435/2 = 217.5 since declared as int it is rounded off to 217 217*5 = 1085 which is the required answer.