3

Can someone tell me why this worked
`int percentHealth = (getHealth() * 100) / maxHealth;`
But this didn't work
`int percentHealth = (getHealth() / maxHealth) * 100;`

It stressed me out for +2 hours.

Comments
  • 1
    I guess some issues with casting?
  • 1
    It probably casted getHealth() as int, or casted (gethealth()/maxhealth()) as int.. then it became 0*100, or worse (0/0)*100
    Try static_cast<float> (or the C# equi) and ckeck the return values.. strange behaviour anyway.
  • 0
    if getHealth() return a float between 0 and 1 then in the second statement the result in the brackets will be always lower than 1, so it will be casted either to 0 or 1.
  • 0
    @2erXre5 edit: it even doesn't work when getHealth() returns an int and maxHealth() returns an int > getHealth(), because the bracket will do a cast to int for a fraction as well..
  • 0
    Brackets imply a casting in C#? Interesting
  • 1
    @ComradeBob sorry to misleading you, no it wont cast (I was in a hurry writing my posts so that error made it through). when an int will be divided by an int, then the result will stay an int, and that is the problem here, because (given getHealth()==75 and maxHealth()==100):

    (75/100)*100 will not result in the expected 75 but in 100, because (75/100)*100 == (1)*100 ==100.

    (75*100)/100 in contradiction will result in (7500)/100 == 75
  • 1
    The next time you spend more than 10 minutes in something "similar", split it and store it into variables, then, look what types have those variables and you may understand what's going on.
  • 0
    As stated above, int typecast:

    75/100 = 0
    75/100.0 = 0.75

    The fix: store `maxHealth` (or both) as a float.
Add Comment