-3

Would someone mind explaining why this doesn't work? All variables except for chance are ints, whereas chance is a double. When I print all the values they are definitely correct... but chance always comes out as 0.0. I know this has something to do with converting ints to doubles, as I have had an issue like this a couple of times before. What is the key to getting it to do what you want?

    gladValue = (glad.dexterity+glad.tactical+weaponSkill);
    oppValue = (glad.target.dexterity+glad.target.tactical+glad.target.agility);
    chance = (gladValue/oppValue)*10.0;

Thanks

Peter F
  • 435
  • 1
  • 8
  • 17

1 Answers1

3

You should write gladValue * 10.0 / oppValue instead.

The reason is quite subtle. Your brackets mean that gladValue / oppValue is computed first. But these variables are integers so the result is an integer and therefore you lose the fraction part. Only when it is multipled by 10.0 will it get promoted to a double; but by then it's too late.

If you do as I say then, bearing mind that * and / have the same precedence and the operations happen from left to right, then when computing gladValue * 10.0, gladValue is promoted to floating point and that floating point result is divided by oppValue.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Is the deal that it takes it's type from the first operation performed? Edit: I see your edit. Thank you. – Peter F Jun 22 '13 at 19:56