Java Double增量 [英] Java Double increment

查看:243
本文介绍了Java Double增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双变种

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修复此问题并返回双精度数字?

In my case the variable shoud be incremented to 2.6 but votexp returns 2.6000000000000005 how can i fix this by using the same double var and return a double precision number ?

推荐答案

您正在累积舍入错误.最简单的方法是使用long(或int并且仅在末尾使用双精度.)(或BigDecimal,并在末尾使用双精度,但这太复杂了)

You are accumulating a rounding error. The simplest thing to do is to use an long (or int and only use a double at the end. (Or a BigDecimal and double at the end, but this is overly complicated)

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进行运算的结果可能会具有太大的错误,无法隐藏.如果您正确地舍入了最后一个结果,则误差将足够小,不会引起问题.

As the Double.toString() "knows" values can be imprecise, it will do a small amount of rounding. This rounding is limited so the result of operating on two double can have an error too large to hide. If you round your last result correctly, the error will be small enough it won't cause a problem.

这篇关于Java Double增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆