我正在尝试使用一个循环来使用PHP计算每月的利率。我得到一个输出,但是数字本身会重复,并且月份也不输出。我如何输出该月,该月赚取的利息以及新的本金余额?
HTML
<form action='displayInterest.php' method ='POST'>
<p>Principal
<input type = 'text' name ='principal' maxlength='20'/>
</p>
<p>Interest Rate
<input type='text' name='interestRate' maxlength = '20'/>
</p>
<p>Term
<input type='text' name='term' maxlength='20'/>
</p>
<input type='submit' value='Calculate Interest'/>
</form>
PHP
<?php
$principal = $_REQUEST['principal'];
$interestRate = $_REQUEST['interestRate'];
$term = $_REQUEST['term'];
$MIR = $interestRate / 12;
$MI = $principal / $MIR;
$MB = $principal + $MI;
$month = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September','October', 'November', 'December');
for($i = 0; $i < 13; $i++){
$MI += $month[0];
echo($MI);
echo('</br>');
}
?>
答案 0 :(得分:0)
您错误地增加了月份,因此,它似乎打破了循环的其余部分。以下应该是您所需要的:
$MIR = $interestRate / 12;
$MI = $principal / $MIR;
$MB = $principal + $MI;
$month = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September','October', 'November', 'December');
for($i = 0; $i < 13; $i++){
$MI = $month[$i];
echo $MI .'<br>';
}
请注意,$ MI变量正在循环中被覆盖,我建议将其更改为其他内容,或者仅输出$ month,例如:
for($i = 0; $i < 13; $i++){
echo $month[$i] .'<br>';
}
答案 1 :(得分:0)
如果您只需要利息值和月份,请在循环中尝试以下代码:
for ($i = 0; $i < 13; $i++) {
$rate = ($principal * $interestRate) / 100;
echo $month[$i] . " => " . $rate;
$principal += $rate;
echo "</br>";
}
答案 2 :(得分:0)
采用利率除以100(在循环之外,以避免每次计算)。
然后假设您的学期以月为单位,则对学期数进行循环 :
<?php
$principal = $_REQUEST['principal'];
$interestRate = $_REQUEST['interestRate'] / 100;
$term = $_REQUEST['term'];
$month = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September','October', 'November', 'December');
$time = 1 / 12; // Getting the "t" for the formula
for ($i = 0; $i < $term; $i++) { // Run the loop for the number of terms
$total = $principal * $interestRate * $time; // Total is interest formula (P * r * t)
$principal += $total; // Add total to principal to calculate for next month
echo "<b>" . $month[$i] . "</b>: Interest: " . $total . ", Principal: " . $principal . "<br/>"; // Output month, interest earned, and new principal
}
?>
我的本金为10000
,利息为5
,期限为5
的输出为:
January: Interest: 41.666666666667, Principal: 10041.666666667
February: Interest: 41.840277777778, Principal: 10083.506944444
March: Interest: 42.014612268519, Principal: 10125.521556713
April: Interest: 42.189673152971, Principal: 10167.711229866
May: Interest: 42.365463457775, Principal: 10210.076693324
您可以根据需要设置输出格式。