此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));

在我看来,它们相同,但是它们返回不同的值。怎么了?

最佳答案

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

09-25 16:44