我目前正在学习javascript。我创建了一个计算器来查找投资未来价值。当它显示时,它给了我一个不正确的值future value
。我已经检查了几次公式,但它仍然给我一个错误。此外,如果兴趣小于0
或大于20
但没有显示任何内容,我已经设置了警报。必要时如何正确显示正确的未来值和警报?例子
Javascript
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value ) /100;
var years = parseInt( $("years").value );
$("futureValue").value = "";
if (isNaN(investment) || investment <= 0) {
alert("Investment must be a valid number\nand greater than zero.");
} else if(isNaN(annualRate) || annualRate <= 0 || annualRate > 20) {
alert("Annual rate must be a valid number\nand less than or equal to 20.");
} else if(isNaN(years) || years <= 0 || years > 50) {
alert("Years must be a valid number\nand less than or equal to 50.");
} else {
//var monthlyRate = annualRate / 12;
//var months = years * 12;
var futureValue = 0;
for ( i = 1; i <= years; i++ ) {
futureValue = ( futureValue + investment ) *
( 1 + annualRate );
}
$("futureValue").value = futureValue.toFixed(2);
}
}
var clear_click = function () {
$("investment").value = "";
$("rate").value = "";
$("years").value = "";
$("futureValue").value = "";
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("investment").focus();
$("clear").onclick = clear_click;
}