遞歸在PHP中的應用舉例

遞歸在PHP中的應用舉例php

<?php
//amortizationTable表示還貸計算函數
function amortizationTable($pNum, $periodicPayment, $balance, $monthlyInterest)
{
//計算支付利息
$paymentInterest = round ($balance*$monthlyInterest, 2);
//計算還款額
$paymentPrincipal = round($periodicPayment - $paymentInterest,2);
//用餘額減去還款額
$newBalance = round($balance-$paymentPrincipal,2);
//若是餘額<每個月還款,設置爲0
if ($newBalance < $paymentPrincipal){
   $newBalance = 0;
}

printf ("<tr><td>%d</td>",$pNum);
printf ("<td>$%s</td>", number_format ($newBalance,2));
printf ("<td>$%s</td>", number_format ($periodicPayment,2));
printf ("<td>$%s</td>", number_format ($paymentPrincipal,2));
printf ("<td>$%s</td></tr>", number_format ($paymentInterest,2));

#if balance not yet zero, recursively call amortizationTable()
if ($newBalance>0){
   $pNum++;
   amortizationTable($pNum, $periodicPayment,
                      $newBalance, $monthlyInterest);
	}else{
	return 0;
	}
}

$balance = 10000.00;                                 // 貸款餘額
$interestRate = 0.0575;                              //貸款利率
$monthlyInterest = $interestRate/12;                 //每個月利率
$termLength = 5;                                     //貸款期限,單位爲年
$paymentsPerYear = 12;                               //每一年支付次數
$paymentNumber = 1;                                  //付款迭代
$totalPayments = $termLength*$paymentsPerYear;       //肯定付款次數
$intCalc = 1 + $interestRate / $paymentsPerYear;     //肯定分期付款的利息部分
$periodicPayment = $balance * pow($intCalc, $totalPayments)*($intCalc -1)/(pow($intCalc,$totalPayments) -1);

//每個月還款額限制到小數點後兩位
$periodcPayment = round($periodicPayment,2);

//建立表
echo "<table width='50%' align = 'center' border = '1'>";
echo "<tr>
      <th>Payment Number</th><th>Balance</th>
	  <th>payment</th><th>Principal</th><th>Interest</th>
	  </tr>";
	  
//建立遞歸函數
amortizationTable ($paymentNumber, $periodcPayment, $balance,$monthlyInterest);
//關閉表
echo "</table>";
?>
相關文章
相關標籤/搜索