所以我接到了一项任务,要编写一个计数器,将给定量的美元和美分加在一起。我们获得了一个用于测试功能的测试类。
我们得到了以下提示:
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
}
}
我意识到我在这里犯了错误(据说是在 float 中并试图计算 float 的美元和美分部分)。但我无法准确指出它失败的地方。
最佳答案
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;
}
}
财务规划的一条非常重要的规则:切勿使用 float 资金作为柜台资金。你肯定很快就会遇到问题,甚至很快就会遇到问题。看我的例子,实际上你的计数器可以很容易地实现,只需将美分数量保存为 int (正如我所看到的,你没有部分美分)。
附注一招成就 future
假设您需要一个浮点值并支持对其进行所有标准数学运算,例如 +,-,/,*
。例如。美元和整数美分(如您的示例中),并且您不能(或不想)使用 float 操作。你应该做什么?
只需将整数值中的两位低位数字保留为小数部分即可。让我们以价格 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
关于java - 美元和美分计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346008/