parseInt(0.08)
給出0
所以數學不會做任何事情。你不需要在這裏解析你的變量,因爲你自己定義它們。如果你從用戶輸入中讀取,你真的只需要解析。
此外,你的興趣數學是不好的。你需要計算利息。
這個腳本給正確*輸出:
var invest;
var rate;
var amount;
rate = 0.08;
invest = 100000;
amount = invest;
for(var i = 1; i <= 10; i++){
amount = amount * (1.0 + rate);
document.write("Annual Account Balance for Year " + i + " = " + amount + "<br>");
}
輸出:
Annual Account Balance for Year 1 = 108000
Annual Account Balance for Year 2 = 116640.00000000001
Annual Account Balance for Year 3 = 125971.20000000003
Annual Account Balance for Year 4 = 136048.89600000004
Annual Account Balance for Year 5 = 146932.80768000006
Annual Account Balance for Year 6 = 158687.43229440006
Annual Account Balance for Year 7 = 171382.42687795206
Annual Account Balance for Year 8 = 185093.02102818823
Annual Account Balance for Year 9 = 199900.4627104433
Annual Account Balance for Year 10 = 215892.49972727877
// this would be the output with your bad math:
Annual Account Balance for Year 1 = 108000
Annual Account Balance for Year 2 = 115999.99999999999 // float funny business, beware!
Annual Account Balance for Year 3 = 124000
Annual Account Balance for Year 4 = 132000
Annual Account Balance for Year 5 = 140000
Annual Account Balance for Year 6 = 148000
Annual Account Balance for Year 7 = 156000
Annual Account Balance for Year 8 = 164000
Annual Account Balance for Year 9 = 172000
Annual Account Balance for Year 10 = 180000
*由於我們正在處理的浮點值這裏要十分小心它的精確度有限。
注意'100,000'評估'100'並返回000',這是嚴格模式下的語法錯誤(在非嚴格模式下可能是'0')。 – Oriol
率,投資,我不是字符串..你爲什麼解析它們? –