首页 > 解决方案 > 美元和美分柜台

问题描述

所以我得到了一个任务来写一个计数器,把给定数量的美元和美分加在一起。我们得到了一个用于测试功能的测试类。

我们得到了以下提示:

public int dollars () //The dollar count. 
ensure: this.dollars () >= 0

public int cents () //The cents count. 
ensure: 0 <= this.cents() && this.cents() <= 99

和:

public void add (int dollars, int cents) //Add the specified dollars and cents to this Counter. 
public void reset () //Reset this Counter to 0. 
ensure: this .dollars() == 0 && this.cents() == 0 

这是我当前的代码:

public class Counter {

    private float count;

    public Counter() {
        count = 0;
    }

    public int dollars() {
        if (this.dollars() >= 0) {
            count = count + Float.parseFloat(this.dollars() + "." + 0);
        } return 0;
    }

    public int cents() {
        if (0 <= this.cents() && this.cents() <= 99) {
            count = count + Float.parseFloat(+0 + "." + this.cents());
        } else if (100 <= this.cents()) {
            count = count + Float.parseFloat(+1 + "." + (this.cents() - 100));
        }
        return 0;
    }

    public void add(int dollars, int cents) {
        dollars = this.dollars();
        cents = this.cents();
    }

    public void reset() {
        count = 0;  
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
}

我意识到我在这里犯了错误(据说是在浮动并试图计算浮动的美元和美分部分)。但我无法准确指出它失败的地方。

标签: javacurrency

解决方案


public final class Counter {

    private int cents;

    public int dollars() {
        return cents / 100;
    }

    public int cents() {
        return cents;    // if you want to retrun all centes
        // return cents % 100;    // if you want to return cents less than dollar
    }

    public void add(int dollars, int cents) {
        this.cents = dollars * 100 + cents;
    }

    public void reset() {
        cents = 0;
    }
}

金融编程的一个非常重要的规则:永远不要使用浮点数作为计价货币。你肯定很快甚至很快就会遇到问题。看我的例子,实际上你的计数器可以很容易地实现,只需将美分的数量保存为 int (如我所见,你没有美分的一部分)。

PS 未来的一招

想象一下,您需要一个浮点值并支持对它们的所有标准数学运算,例如+,-,/,*. 例如美元和整数美分(如您的示例中),您不能(或不想)使用浮动操作。你该怎么办?

只需保留整数值中的两个低位数字作为小数部分。让我们以 12 美元的价格为例:

int price = 1200;    // 00 is reserverd for centes, , price is $12
price += 600;        // add $6, price is $18
price += 44;         // add $0.44, price is $18.55

int dollars = price / 100;   // retrieve total dollars - $18     
int cents = cents % 100;     // retrieve cents less than dollars - 44  

推荐阅读