美文网首页
第 60 条:如果需要精确的答案,请避免使用float和doub

第 60 条:如果需要精确的答案,请避免使用float和doub

作者: 综合楼 | 来源:发表于2021-06-08 19:59 被阅读0次
如果需要精确的答案,请避免使用float和double.jpeg
// Broken - uses floating point for monetary calculation!
public static void main(String[] args) {
    double funds = 1.00;
    int itemsBought = 0;
    for (double price = 0.10; funds >= price; price += 0.10) {
        funds -= price;
        itemsBought++;
    }
    System.out.println(itemsBought + " items bought.");
    System.out.println("Change: $" + funds);
}
public static void main(String[] args) {
    final BigDecimal TEN_CENTS = new BigDecimal(".10");
    int itemsBought = 0;
    BigDecimal funds = new BigDecimal("1.00");
    for (BigDecimal price = TEN_CENTS;
    funds.compareTo(price) >= 0;
    price = price.add(TEN_CENTS)) {
        funds = funds.subtract(price);
        itemsBought++;
    }
    System.out.println(itemsBought + " items bought.");
    System.out.println("Money left over: $" + funds);
}
public static void main(String[] args) {
    int itemsBought = 0;
    int funds = 100;
    for (int price = 10; funds >= price; price += 10) {
        funds -= price;
        itemsBought++;
    }
    System.out.println(itemsBought + " items bought.");
    System.out.println("Cash left over: " + funds + " cents");
}

相关文章

网友评论

      本文标题:第 60 条:如果需要精确的答案,请避免使用float和doub

      本文链接:https://www.haomeiwen.com/subject/deusjltx.html