Javascript每年复利计算

时间:2015-06-24 23:19:10

标签: javascript parseint parsefloat

此代码运行时,每年输出“年度(i)年度帐户余额= 100”。很明显,每次答案都不应该是100,但我无法看到我在等式中做错了什么。

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 个答案:

答案 0 :(得分:1)

不是打电话给parseInt(rate),而是需要拨打parseFloat(rate) - 虽然根据您的代码,这些是数字 - 因此无论如何都不需要解析它们。

parseInt将从字符串中解析整数(尽管它仍然是类型&#39; Number&#39;)。在这种情况下,它实际上返回0而不是您想要使用的0.08。在数字上调用parseInt会将数字从数字转换为字符串,然后再返回......这实际上是无用的。

此外,正如Oriol所述,您无法在JavaScript中为数字添加逗号。

答案 1 :(得分: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

*由于我们处理浮动值,因此要非常谨慎,因为它的精度有限。