-1

I'm running this snippet of code:

int x, y;
float val1, val2, val3;
x = 20;
y = 25;
val1 = x - 10;
val2 = y/val1;
val3 = float(val2);
val4 = float(y/(x-10));

The above outputs:

val1 = 10
val2 = 2.5
val3 = 2.5
val4 = 2

Can anyone explain to me why val3 and val4 evaluate differently? , when in fact they're both doing the same calculations?

B.1988
  • 35
  • 2
  • 7

2 Answers2

0

(y/x-10) is dealing with integers. The float isn't applied until after this calculation, which would produce 2.

y and x are both integers. So, 20 (value of x) - 10 = 10. Then 25 / 10 (still dealing with integers - no floats yet) = 2.

Gavin
  • 4,365
  • 1
  • 18
  • 27
0

They are evaluated differently.

val3 = float(y / float(x - 10))
val4 = float(y / (x - 10)

For val3, the types are float(int / float) and val4 is float(int / int) which will cast the result of y / (x - 10) to int first and then cast it to float.

Pan Long
  • 1,024
  • 1
  • 9
  • 16