您的位置:首页 > 职场人生

1元钱可以买多少个糖果--面试题

2017-08-12 02:37 211 查看
import java.math.BigDecimal;
import java.text.DecimalFormat;
/*
需求:
假设你的口袋里有1元(也可以是n元),你看到货架上有一排糖果,标价分别为1角、2角、3角、4角等等,一直到1元;
你打算从标价为1角的开始,每种买1个,
一直到不能支付下一种价格的糖果为止,那么你可以买多少个糖果?还会找回多少零钱?
*/
public class BuyCandy {

public static void main(String[] args) {
firstMethod();
System.out.println("--------------------");
secondMethod() ;
}

public static void firstMethod() {//第一种方法
double funds = 1.00;// 资金
int itemsBought = 0;// 购买的个数
DecimalFormat df = new DecimalFormat("#.00");
for (double price = 0.10; funds >= price; price += 0.10) {
funds -= price;
funds = Double.parseDouble(df.format(funds));
itemsBought++;
}
System.out.println(itemsBought + " items bought.");// 购买的个数
System.out.println("Change: " + funds);// 余额
}

public static void secondMethod() {//第二种方法
int itemsBought = 0;
BigDecimal funds = new BigDecimal("1.00");
final BigDecimal TEN_CENTS = new BigDecimal("0.10");
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("Money left over: " + funds);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 面试题
相关文章推荐