Java 双倍增量

标签 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;
}

在我的例子中,变量应该增加到 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/

相关文章:

java - Log4j 不支持二进制日志记录格式?

java - 接口(interface)常量有什么用?

c++ - 浮点比较精度

python - 有人可以解释这种浮点行为吗?

javascript - 将具有 IEEE-754 double 十六进制表示的字符串转换为 JavaScript 数字变量

c# - 为什么 float.MaxValue 0xFF 0xFF 0x7F 0x7F 而不是 0x7F, 0xFF, 0xFF, 0xFF 之类的整数?

java - Eclipse 市场 - Maven 集成

java - 在 WEAR OS 上启动 map 需要 WRITE_SETTINGS 权限

java - 开始 Java SudokuSolver FileNotFoundException

java - 使用 Double 做财务软件