1

I might have been staring at my screen too much because of programming, but I really don't understand what is happening here.

I'm trying to make a game and calculate the percentage progress it takes to level up. Here are my methods:

public static int currentLevelInt(Integer XP){
    return (int)(1 + sqrt(1+8*XP/50))/2;
}

public static double currentLevelDouble(Integer XP){
    return (1 + sqrt(1+8*XP/50))/2;
}

public static int getPercentage(Integer XP){
    double currentLevel = currentLevelDouble(XP);
    int nextLevel = currentLevelInt(XP)+1;
    return (int)(100-((nextLevel-currentLevel)*100));
}

Let's say I have 54 XP. Then these are the expected values:

currentLevelInt(54) = 2
currentLevelDouble(54) = 2.05241747
(int)(100-(((currentLevelInt(54)+1)-currentLevelDouble(54))*100)) = 5%
//+1 because I need the next Level

But these are the values I get returned:

currentLevelInt(54) = 2
currentLevelDouble(54) = 2.0
(int)(100-(((currentLevelInt(54)+1)-currentLevelDouble(54))*100)) = 0%
//+1 because I need the next Level

I don't understand what is going on? I'm passing the double as double, why would it be rounded off to 2.0?

Dysanix Official
  • 742
  • 1
  • 7
  • 17
  • 2
    this `1+8*XP/50` is all `int` so the result will automaticly be an `int` (the biggest from the expression). Then, you have `1 + sqrt(1+8*54/50))/2` -> `1 + sqrt(9))/2` – AxelH Jan 24 '17 at 06:39
  • @AxelH Wow, I have never encountered this problem or noticed it before in all my programming time. How do I get around this, do I use the Math library? – Dysanix Official Jan 24 '17 at 06:41
  • Just turn any of the operands of your division to a `double` - e.g. by using `/50.0`. Alternatively, you can also use a cast which might make the intention more explicit. – Hulk Jan 24 '17 at 06:43
  • @Hulk Oh I see, so if I turn everything into doubles it should work, like so: `(1.0 + sqrt(1.0+8.0*XP/50.0))/2.0` and the XP into a double too? – Dysanix Official Jan 24 '17 at 06:45
  • Yes, but one would be enough - either `8.0` or `((double)XP)` or `50.0` should be sufficient. – Hulk Jan 24 '17 at 06:47
  • @Hulk, not any ! it need to be the divider because the type will define during the evaluation so `8.0 + 52/50` will gave `8.0 + 1` since the division will be done first ( int / int -> int). Set this using the priority of operator -> `8+52/50.0` – AxelH Jan 24 '17 at 07:02
  • @AxelH but the expression mentioned by the OP is `8.0 * XP / 52`, not `8.0 + 52/50` (and I explicitly said "any of the operands *of your division*"). `8.0 * 50 / 52` yields 7.6923076923076925, just like `8*50.0/52` or `8*50/52.0`. – Hulk Jan 24 '17 at 10:16
  • @Hulk My bad, it was `1+8*XP` not `8+XP`. but the comment is still ok. The usage or cast in double should be done on the first operand used where a floating value might append. – AxelH Jan 24 '17 at 10:17

0 Answers0