Reputation:
Bear with me: I have a very simple comparison, between a value, contained in a dictionary, which is an int, and a float.
Before the comparison, I divide the value by 100, so I get a decimal value (the int is 50, divide by 100, get 0.5).
baseline = 0f;
if ((mydict["intvalue"] / 100) > baseline)
...do something
0.5 is greater than 0.0, so it should "do someting".
Now, the comparison fail all the times; because an int divided by 100, where the result is between 0 and 1, will end up being an int with value 0, from what I can see. I did cast the value; to solve the issue, but VS tell me that the cast is redundant; and either way, the result is still 0. I don't get what I am doing wrong here.
baseline = 0f;
if ((float)(mydict["intvalue"] / 100) > baseline)
...do something
The compiler tell me that the cast is not necessary, but even if I leave the cast there; I still get 0.
Upvotes: 1
Views: 380
Reputation: 161
(float)(mydict["intvalue"] / 100) > baseline
this code run in this order.
mydict["intvalue"]=50
(float)(mydict["intvalue"] / 100) > baseline => (float)(50 / 100) > baseline
50 / 100 = 0 here is the problem
(float)(50 / 100) > baseline => (float)0 > baseline
(float)0=0.0f
(float)0 > baseline => 0.0f>0.0f =>false
Upvotes: 0
Reputation: 5764
Your code
if ((float)(mydict["intvalue"] / 100) > baseline)
says: Get int divde by int and result also int cast to float. So you need to modify code to operate on floats:
if (((float)mydict["intvalue"] / 100) > baseline)
or
if ((mydict["intvalue"] / 100f) > baseline)
Upvotes: 0
Reputation: 1561
Or implicit cast like this
if (mydict["intvalue"] / 100f > baseline)
Upvotes: 0
Reputation: 30813
That is because the float
casting should be done in one of the items (either mydict["intvalue"]
or 100
) and not their result:
//here is one correct way of doing it
if (((float)mydict["intvalue"] / 100) > baseline)
//alternatively
if ((mydict["intvalue"] / 100f) > baseline)
What you do before is having integer division, and then you cast to float and therefore it is redundant:
//note that here you do division first before casting to float
if ((float)(mydict["intvalue"] / 100) > baseline)
Upvotes: 3