首页 技术 正文
技术 2022年11月20日
0 收藏 837 点赞 2,442 浏览 1226 个字

题目: 假设你口袋里有1$,看到货架上有一排美味的糖果,标价分别为0.10$,0.20$,0.30$…1$,你打算从标价为0.10$的糖果开始买起,每种买一颗,一直到不能支付货架上下一种价格的糖果为止,那么可以买多少颗糖果?还可以找回多少零钱?

使用double的程序如下:

double funds = 1.00;
int itemsBought = 0;
for(double price=.10;funds>=price;price+=.10){
funds -= price;
itemsBought++;
}
System.out.println(itemsBought+" items bought.");
System.out.println("change:$"+funds);

返回结果如下:
3 items bought.
change:$0.3999999999999999

这个答案是不正确的,解决方案是使用BigDecimal,int或者long进行货币计算

使用BigDecimal的程序如下:

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)){
itemsBought++;
funds = funds.subtract(price);
}System.out.println(itemsBought+" items bought.");
System.out.println("change:$"+funds);

返回结果如下:
4 items bought.
change:$0

这个结果是正确的。

使用int的程序如下(需将1.00$先转换为100cents):

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("change:$"+funds);

返回结果如下:
4 items bought.
change:$0

这个结果也是正确的。

所以:
1)如果需要通过法定要求的舍入行为进行业务计算,使用BigDecimal是非常方便的;
2)如果性能非常关键,而且又不介意记录十进制小数点,而且所涉及的数值又不太大,就可以使用int或long,
3) 如果数值范围没超过9位十进制数字,就可以使用int,如果数值范围没超过18位十进制数字,可以使用long,如果数值范围超过了18位十进制数字,就必须使用BigDecimal。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898