Thread: CH5 pg 150 While Loops View Single Post
November 4th, 2003, 01:10 PM
nikolai
Friend of Wrox
 Points: 2,570, Level: 21
 Activity: 0%

Join Date: Jun 2003
Location: San Diego, CA, USA
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts

Okay, Wade -- you seriously need to step back and just look at your code. Make up some numbers, grab a pencil and paper (or use a whiteboard, as I prefer), and trace through your code. Take a look for yourself what's happening. Come up with some sample values for your variables, write them down, and keep track of each variable value as your code runs.

When I read the code, I wonder why you have a while() loop at all. I mean, Rich is correct in diagnosing your problem -- an infinite loop... but why are you looping at all? What is it your loop is meant to do?

The way I read it, a user submits a loan amount and a monthly payment, and you calculate how long it'll take to pay off that loan at that monthly rate.

The reason you're using a loop is because each iteration of the loop represents a month's payment. After each iteration, the loan balance *should* go down -- that implies that you WILL approach a zero balance sooner or later.

If the balance does NOT change, or worse, it rises, then you've got a problem -- your monthly payment either matches or is less than the interest charge for that month. Your script does test for this, but it tests for it within the body of the loop and doesn't exit the loop if the test fails, which will also cause an infinite loop.

Here's my suggested rewrite of your code:

<?php

switch (\$_POST["loan"])
{
case '1000': // \$_POST['loan'] is a STRING, not an integer.
{
\$interest = .05; // 5%
}
break;

case '5000':
{
\$interest = .065; //6.5%
}
break;

case '10000':
{
\$interest = .08; // 8%
}
break;

default:
{
echo "You didn't choose a loan package.\n";
exit;
}
}

\$balance = round((float)\$_POST['loan'], 2); // convert to float
\$monthly = round((float)\$_POST['month'], 2); // ditto

// Before we start the loop, test whether the monthly
// payment is enough to cover the interest:
\$first_month_interest = round((\$balance * \$interest), 2);

if ((\$first_month_interest) >= \$montly)
{
echo "You will never pay off the loan. "
. "Your monthly payment is too low.\n";
exit;
}

for (\$duration = 0; \$balance > 0; ++\$duration)
{
\$balance = round(\$balance * (1 + \$interest) - \$monthly, 2);
}

echo "It would take {\$duration} months to pay off this loan at ";
printf("%.1f", (\$interest * 100)); // nicely formats float
echo "%.\n";

?>

I hope this version makes a little more sense...

Take care,

Nik
http://www.bigaction.org/