I am having problems with:
int q = 150;
float s = 0.7f;
float z = q*s;
int z1 = (int) (q*s);
int z2 = (int) z;
The result is
z1 int with value 104z2 int with value 105
Can anyone explain this? I do not understand these results.
To avoid closure, I (René Vogt) add this information:
q*sresults in a floatvalue 105.0f(or perhaps 104.999999, but the string representation ends as 105).- therefore
zis floatof105
the question now is, why (int)zleads to 105, but (int)(q*s)leads to 104? I can reproduce this on my machine (i7, Win10, VS2015, .NET4.6.1)
And the IL code:
// Initialisation
// q = 150
ldc.i4 0x96
stloc.0
// s = 0.7f
ldc.r4 0.69999999
stloc.1
// calculating z
ldloc.0 // load q
conv.r4 // convert to float
ldloc.1 // load s
mul // q*s
stloc.2 // store float result to z
// calulating z1
ldloc.0 // load q
conv.r4 // convert to float
ldloc.1 // load s
mul // q*s
conv.i4 // convert to int
stloc.3 // store int result in z1 => 104!
// calculating z2
ldloc.2 // loading float z
conv.i4 // converting to int
stloc.s // write to z2 (last local variable -> "s" as stack address)
// => 105
, , z1 z2 , z2 float (z). ?