Georges Kayembe Georges Kayembe - 1 month ago 8
PHP Question

what's wrong with my while-loop php

Create a while-loop that subtracts 6.82 from the number 761 until the
number is between (not equal to) 23 and 33. Answer with the final result asa float, rounded to 2 decimals.

$f=761;
$b=6.82;
while (($f > 33)||($f < 23 )) {
$f=$f-$b;
$f++;

}
$ANSWER = round($f, PHP_ROUND_HALF_DOWN);


I get the wrong answer, 27.68 instead of 31.26 on the book

Answer

I have checked your loop, and before last $f equals 33.5 because of $f++; so it will loop once more. It is like:

f = 50.96
f = 45.14
f = 39.32
f = 33.5 // still higher than 33 so do it once more
f = 27.68 // and now is lower, get out

It seems like $f++ is not necessary here.

You can check both codes:

PHP Compiler