为什么这个数学函数在Java和JavaScript中返回不同的值?

时间:2015-05-07 16:46:37

标签: java javascript math

此JavaScript代码返回115.3:



function FV(rate, nper, pmt, pv, type) {
    var pow = Math.pow(1 + rate, nper);
    var fv;
    if (rate) {
        fv = (pmt*(1+rate*type)*(1-pow)/rate)-pv*pow;
    } else {
        fv = -1 * (pv + pmt * nper);
    }
    return fv.toFixed(2);
}

document.write(   FV(0.06/12,12,-(2750+1375)/12,-0,0)-(0+2750+1375)    )




此Java代码返回106.1:

public double FV(double rate, double nper, double pmt, double pv, int type) {
    double pow = Math.pow(1 + rate, nper);
    double fv;        
    if (rate > 0) {
        fv = (pmt*(1+rate*type)*(1-pow)/rate)-pv*pow;
    } else {
        fv = -1 * (pv + pmt * nper);
    }
    return fv;
}
System.out.println(FV(0.06/12,12,-(2750+1375)/12,-0,0)-(0+2750+1375));

它们看起来和我一样,但它们会返回不同的值。怎么了?

1 个答案:

答案 0 :(得分:26)

在JavaScript中-(2750+1375)/12评估为-343.75。在Java中,它的计算结果为-343,因为在Java中划分整数时,会得到整数结果。要解决此问题,只需将表达式替换为-(2750+1375)/12.0