0

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?

ClashClown
  • 63
  • 1
  • 7

7 Answers7

4

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;
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
2

this saves in result of each part as an int

so

435 / 2 == 217
217 * 5 == 1085
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

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
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

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

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

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
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

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.

  1. Assigning x = 435;
  2. Dividing first y = x / 2; // This stores y= 217
  3. And then it multiplies y=y*5; // Finally y= 1085

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.

Prateek Mishra
  • 1,226
  • 10
  • 21
0

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.