我有一个双变量
public double votes(){
double votexp = 0;
for(Elettore e:docenti.values()){
if(e.getVoto()==true) //everytime this is true increment by 1
{
votexp+=1.0;
}
}
for(Elettore e:studenti.values()){
if(e.getVoto()==true) //everytime this is true increment by 0.2
{
votexp+=0.2;
}
}
for(Elettore e:pta.values()){
if(e.getVoto()==true) //everytime this is true increment by 0.2
{
votexp+=0.2;
}
}
return votexp;
}
在我的例子中,变量应该增加到 2.6,但 votexp 返回 2.6000000000000005 我如何通过使用相同的 double var 并返回 double 字来解决此问题?
最佳答案
您正在累积舍入误差。最简单的做法是使用 long
(或 int
并仅在末尾使用 double。(或者使用 BigDecimal 并在末尾使用 double,但这太过分了)复杂)
public double votes() {
long votexp = 0;
for (Elettore e : docenti.values())
if (e.getVoto()) //everytime this is true increment by 1
votexp += 10;
for (Elettore e : studenti.values())
if (e.getVoto()) //everytime this is true increment by 0.2
votexp += 2;
for (Elettore e : pta.values())
if (e.getVoto()) //everytime this is true increment by 0.2
votexp += 2;
return votexp / 10.0;
}
<小时/>
double a = 26 / 10.0;
System.out.println(a);
打印
2.6
由于 Double.toString()“知道”值可能不精确,因此它将进行少量舍入。这种舍入是有限的,因此对两个 double
进行操作的结果可能会出现太大而无法隐藏的错误。如果您正确地舍入最后的结果,则误差将足够小,不会导致问题。
关于Java 双倍增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9413908/