我目前在學習javascript。我創建了一個計算器來查找投資未來的價值。當它顯示future value
時,它給我一個不正確的值。我已經檢查了幾次,但它仍然給我一個錯誤。此外,如果利息小於0
或大於20
,但我沒有顯示任何信息,則設置了警報。如何在必要時能夠正確顯示正確的未來價值和警報? Example用javascript計算投資值
的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;
}
您可以給出示例輸入和預期輸出以及您正在獲得的輸出嗎? – Jon 2013-04-04 21:15:01
在附註中,我認爲你沒有檢查'annualRate'的正確值,因爲你所做的第一件事是除以'100',所以你應該檢查'> .2' – Jon 2013-04-04 21:22:21