double x = 0;
double P = 0.327; //P is a actually function that return double and change all the time
double w1 = 1/4; //prints 0 (w1 and w2 are same as P)
double w2= 10/4; //prints 2
x=x+P*w1+(1-P)*w2;
System.out.println(x); // prints 1.346 and the real result is 1.76425
我不知道如何克服四舍五入的 double 问题,我尝试了 BigDecimal,也许我做的不对..
我不需要非常精确的结果,但我确实需要结果 1.764。 提前致谢。
最佳答案
1/4
和10/4
是整数除法。他们的结果是一个整数,然后扩大到一个 double 。你想要的是双师:
double w1 = 1.0 / 4
或
double w1 = 1 / 4.0
关于java - double 被四舍五入而不精确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23031587/