浮点值的舍入问题

时间:2018-07-17 23:46:05

标签: java floating-point precision subtraction

我创建了一个程序来递归计算找零所需的最少硬币数量。但是当我尝试0.41时,我希望返回4(0.25、0.1、0.05、0.01),但返回3。

我调试了程序,发现当程序到达从0.16减去0.1的点时,结果为0.05999995。为什么会这样,我怎么能通过呢?

其他一些线程建议使用BigDecimal,但最初我在C中尝试了此问题,当它失败时,我去了Java检查那里是否发生了同样的事情。使用C进行编程时是否有解决方法?

以下代码:

public static int calculate_coins(float total){
    if(total == 0){
        return 0;
    }

    if(total >= 0.25){
        return 1 + calculate_coins(total - (float)0.25);
    }

    if(total >= 0.1){
        return 1 + calculate_coins(total - (float)0.1);
    }

    if(total >= 0.05){
        return 1 + calculate_coins(total - (float)0.05);
    }

    if(total >= 0.01){
        return 1 + calculate_coins(total - (float)0.01);
    }

    return 0;
}

0 个答案:

没有答案