【发布时间】:2021-07-12 13:14:52
【问题描述】:
这是一个家庭作业问题,但我在问我的错误在哪里。我一直在寻找,看不到我哪里出错了。当我运行应用程序时,我收到以下错误:
未定义变量:monthly_rate
在这一行:$monthly_rate_f = number_format($monthly_rate, 2).'%';
这是应用程序的完整代码:
<?php
// get the data from the form
$investment = filter_input(INPUT_POST, 'investment', FILTER_VALIDATE_FLOAT);
$interest_rate = filter_input(INPUT_POST, 'interest_rate', FILTER_VALIDATE_FLOAT);
$years = filter_input(INPUT_POST, 'years', FILTER_VALIDATE_INT);
// validate investment
if ($investment === FALSE ) {
$error_message = 'Investment must be a valid number.';
} else if ( $investment <= 0 ) {
$error_message = 'Investment must be greater than zero.';
// validate interest rate
} else if ( $interest_rate === FALSE ) {
$error_message = 'Interest rate must be a valid number.';
} else if ( $interest_rate <= 0 ) {
$error_message = 'Interest rate must be greater than zero.';
// validate years
} else if ( $years === FALSE ) {
$error_message = 'Years must be a valid whole number.';
} else if ( $years <= 0 ) {
$error_message = 'Years must be greater than zero.';
} else if ( $years > 30 ) {
$error_message = 'Years must be less than 31.';
// set error message to empty string if no invalid entries
} else {
$error_message = '';
}
// if an error message exists, go to the index page
if ($error_message != '') {
include('index.php');
exit();
}
// calculate the future value
$future_value = $investment;
if (isset($_POST["monthly"])) {
$compounded_monthly = "Yes";
$months = $years * 12;
$monthly_rate = $interest_rate / 12;
for ($i = 1; $i <= $months; $i++) {
$future_value = $future_value + ($future_value * $monthly_rate * .01);
}
} else {
for ($i = 1; $i <= $years; $i++) {
$future_value = $future_value + ($future_value * $interest_rate * .01);
}
}
// apply currency and percent formatting
$investment_f = '$'.number_format($investment, 2);
$yearly_rate_f = $interest_rate.'%';
$future_value_f = '$'.number_format($future_value, 2);
$monthly_rate_f = number_format($monthly_rate, 2).'%';
?>
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" type="text/css" href="main.css"/>
</head>
<body>
<main>
<h1>Future Value Calculator</h1>
<label>Investment Amount:</label>
<span><?php echo $investment_f; ?></span><br>
<?php
if (isset($_POST["monthly"])) {
echo "<label>Monthly Interest Rate:</label>";
echo "<span>".$monthly_rate_f."</span><br>";
echo" <label>Number of Months:</label>";
echo "<span>".$months."</span><br>";
echo" <label>Future Value:</label>";
echo"<span>".$future_value_f."</span><br>";
echo"Compound Monthly:".$compounded_monthly."</br>";
} else {
echo "<label>Yearly Interest Rate:</label>";
echo "<span>".$yearly_rate_f."</span><br>";
echo" <label>Number of Years:</label>";
echo "<span>".$years."</span><br>";
echo" <label>Future Value:</label>";
echo"<span>".$future_value_f."</span><br>";
}
?>
</main>
</body>
</html>
【问题讨论】:
标签: php phpmyadmin