T. H.
T. H.

Reputation: 79

variable output from while loop not as expected

I'm trying to make a small piece of code that checks amount of items needed to reach a certain level, as you increase in level the amount of exp you get per item increases, in this case it's your level*10.

But it seems as though from what I've tried that the if statement is completely ignored, I don't really know how to proceed from here.

This is the piece of PHP code:

$currentexp = 0;
$currentlevel = 1;
$nextlevel = 83; //value is experience
$goallevel = 13034431; //value is experience
$itemamount = 0;
$itemexp = $currentlevel * 10;

while ($currentexp < $goallevel) {
    $currentexp = $currentexp + $itemexp;
    $itemamount = $itemamount + 1;
    if ($currentexp > $nextlevel) {
        $nextlevel = $nextlevel * 1.10408986946;
        $currentlevel = $currentlevel + 1;
    }
}

echo "You will need " . $itemamount . " items for your goal level";

The output of $itemamount should be some odd 15000 given the start and end point..

Upvotes: 0

Views: 59

Answers (1)

Philipp Palmtag
Philipp Palmtag

Reputation: 1328

while loop and if condition are executed.That is what i can tell so far. $itemamount is increased by one by every iteration. So its a much as $goallevel. Your variables in your loop condition do not change, so its executed for every $goallevel

    $currentexp = 0;
    $currentlevel = 1;
    $nextlevel = 83; //value is experience
    $goallevel = 13034431; //value is experience
    $itemamount = 0;
    $itemexp = 10;

    while ($currentexp < $goallevel) {
        $currentexp = $currentexp + $itemexp;
        $itemamount = $itemamount + 1;
        if ($currentexp > $nextlevel) {
            $nextlevel = $nextlevel * 1.10408986946;
            $currentlevel = $currentlevel + 1;
            $itemexp = $currentlevel * 10;
        }
    }

    echo "You will need " . $itemamount . " items for your goal level".PHP_EOL;

Output is: You will need 11766 items for your goal level

Update

Somehow your experience calculation is wrong. When using a fixed table like in the Excel sheet, I get the correct values, see this example (I shortened the experience table!):

$currentexp = 0;
$currentlevel = 1;
$goallevel = 13034431; //value is experience
$itemamount = 0;
$itemexp = 10;


$exp_borders = [
    0,
    83,
    174,

    // [...] shortened!

    8771558,
    9684577,
    10692629,
    11805606,
    13034431,
];

while ($currentexp < $goallevel) {
    $currentexp = $currentexp + $itemexp;
    $itemamount = $itemamount + 1;
    if ($currentexp > $exp_borders[$currentlevel]) {
        $currentlevel = $currentlevel + 1;
        $itemexp = $currentlevel * 10;
    }
}

echo "You will need " . $itemamount . " items for your goal level".PHP_EOL;

Output is like expected: You will need 15057 items for your goal level

Upvotes: 1

Related Questions