Java双增量

Luc*_*che 0 java ieee-754

我有一个双变量

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;
}
Run Code Online (Sandbox Code Playgroud)

在我的情况下,变量应该增加到2.6但是votexp返回2.6000000000000005我如何通过使用相同的双变量并返回双精度数来解决这个问题?

Pet*_*rey 6

您正在累积舍入错误.最简单的方法是使用long(或者int只使用最后的一个.)(或者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;
}
Run Code Online (Sandbox Code Playgroud)
double a = 26 / 10.0;
System.out.println(a);
Run Code Online (Sandbox Code Playgroud)

版画

2.6
Run Code Online (Sandbox Code Playgroud)

由于Double.toString()"知道"值可能不精确,它将进行少量舍入.这种舍入是有限的,因此对两个操作的结果double可能有一个太大而无法隐藏的错误.如果你正确地舍入你的最后一个结果,错误将足够小,不会导致问题.