views:

54

answers:

3
private final static int L1_MAX_SCORE = 30;
private final static int L2_MAX_SCORE = 150;

public void UpdateLevel(int score) {
   double progress;

   //returns 0.0
   progress = score / (L2_MAX_SCORE  - L1_MAX_SCORE) * 100;   

   //works correctly.
   progress = (double) score / (L2_MAX_SCORE  - L1_MAX_SCORE) * 100;  

Thanks.

+1  A: 

Arithmetic operations in Java whose operands are all ints will result in ints, so you're actually assigning an integer result to a double variable. Thus you must cast at least one of them to a double so that the calculations are performed based on doubles, because of the higher precision.

BoltClock
I find it strange that defining the variable (progress) as a double doesn't automatically initiate this behavior.
Java evaluates the expression on the right hand side first before assigning it to the variable, so I believe by the time the data type is taken into account the result is already an int if you don't cast.
BoltClock
Why would the type of double affect the computation? Store an int as a double is valid, and dividing ints and expecting an int is valid. So `double progress = 3/4; progress == 0` is a completely legitimate statement. If it automatically set 3/4 to be float division, how would you change the syntax so that you can do what it does now?
Falmarri
+2  A: 

Dividing an integer with an integer is defined to do integer division, just like in most (all?) other C-like languages.

By casting score to a double, you are dividing a floating-point value with an integer, and you get a floating-point value back.

Michael Madsen
A: 

L2_MAX_SCORE - L1_MAX_SCORE = 150 - 30 = 120

Let's assume score is 30

Using floating point, the answer should be 30/120 = 0.4 With integer division, this will get rounded to 0 hence why it 'doesn't work' - it is actually working, but doing the wrong kind of division for your needs

You can either

  • a) Cast either numerator or denominator as double
  • b) Rearrange the formula to be (score * 100) / (L2_MAX_SCORE - L1_MAX_SCORE)
    • with this, it would become (30 * 100) / 120 = 3000 / 120 = 40
    • it still does integer division, so if the score is 31 your answer (3100 / 120) is not 25.8333 but 25
Alok
Even if the answer is > 1, the double object still gets populated with 0 without a cast.
What value are you using for the score? `UpdateLevel(110)` should result in 0.0; while `UpdateLevel(120)` will be 100.0
Alok