简体   繁体   English

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

[英]Why does this math function return different values in Java and JavaScript?

This JavaScript code returns 115.3: 此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) ) 

This Java code returns 106.1: 此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));

They look the same to me, but they return different values. 它们看起来和我一样,但它们会返回不同的值。 What's wrong? 怎么了?

In JavaScript -(2750+1375)/12 evaluates to -343.75 . 在JavaScript中-(2750+1375)/12评估为-343.75 In Java it evaluates to -343 , because in Java when you divide integer numbers, you get integer result. 在Java中,它的计算结果为-343 ,因为在Java中划分整数时,会得到整数结果。 To fix this simply replace the expression with -(2750+1375)/12.0 . 要解决此问题,只需将表达式替换为-(2750+1375)/12.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM