B.1988 B.1988 - 2 months ago 20
C++ Question

Evaluating mathematical operations

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?

Answer

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.