I am working on a 'skill calculator' however i have ran into this problem. when putting 3 into the input field it displays the experience from 2... when putting 2 into the input field it's a null which is level 1... it's the same with all numbers up to 100 it displays the lower numbers experience 56 will display 55 experience.

function levelToExperience(goalLevel) {
        var experience = 0;

        for(var curLevel = 1 ; curLevel < goalLevel; curLevel += 1) {
            experience = Math.floor(10 * Math.pow(curLevel, 3) - 10);
        }

        return Math.floor(experience);
    }

    // Convert experience to level
    function experienceToLevel(goalExperience) {
        var curExperience = 0;

        for(var level = 1; level < 100; level += 1) {
            curExperience += Math.floor(Math.floor(10 * Math.pow(level, 3)) - 10);

            if(curExperience > goalExperience) {
                break;
            }
        }

        return level;
    }

This calculation i am using 10L3 − 10 (L = level) level 2 = 70 exp so i can't understand why 2 is showing 0 and 3 is showing 2's experience.

1 Answers

2
user2340824 On Best Solutions
for(var curLevel = 1 ; curLevel < goalLevel; curLevel += 1) {

The problem is this loop. When you pass 2 into it, you continue if curLevel is less than goalLevel, which is 2.

So you do Math.floor(10 * Math.pow(1, 3) - 10) which is 0. Then curLevel is incremented, however, curlevel isn't less than 2, so you exit returning 0.


You don't have to loop, I think you just want to know how much experience to level to the goal.

function levelToExperience(goalLevel) {
   return Math.floor(10 * Math.pow(goalLevel, 3) - 10);
}

Likewise, your experienceToLevel, can be greatly reduced if you take the Cube Root of the value:

function experienceToLevel(goalExperience) {
  return Math.cbrt((goalExperience + 10)/10);
}