2015-06-24 92 views
-2

此代碼運行時,它會輸出「年度(i)= 100」的年度帳戶餘額。很明顯,答案不應該是100次,但我看不出我在做什麼錯誤的方程。Javascript年複利計算

var invest; 
var rate; 
var amount; 

rate = 0.08; 
invest = 100,000; 

    for(var i=1;i<=10;i++){ 
     amount = ((parseInt(invest)) * (1.0 + (parseInt(rate)) * (parseInt(i)))) 
     document.write("Annual Account Balance for Year " + i + " = " + amount + "<br>"); 
    } 
+2

注意'100,000'評估'100'並返回000',這是嚴格模式下的語法錯誤(在非嚴格模式下可能是'0')。 – Oriol

+1

率,投資,我不是字符串..你爲什麼解析它們? –

回答

1

與其說parseInt(rate)的,你需要調用parseFloat(rate) - 儘管根據你的代碼,這些都是數字 - 所以他們不需要無論被解析。

parseInt將從字符串中解析整數(雖然它仍然是「數字」類型)。在這種情況下,它實際上會返回0而不是您想要使用的0.08。在一個數字上調用parseInt會將其從一個數字轉換爲一個字符串,然後再返回......這實質上是無用的。

此外,正如Oriol所述,您不能在JavaScript中爲數字添加逗號。

+1

爲什麼需要'parseFloat'?他們已經是數字。 'parseFloat'將首先將數字轉換爲字符串,然後將其解析爲數字。 – Oriol

+0

我剛抓住它,並將其添加到我的編輯。 – johnnyRose

0

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 

*由於我們正在處理的浮點值這裏要十分小心它的精確度有限。