- public class StoreMoney
- {
- public static void main(String[] args)
- {
- //int allowance = 20; //每天20元零用钱
- //int voerHead = 10; //周一到周六的开销
- //int target = 100; //目标:存够100元
- //storeMoney(allowance, overHead, target);//传入对应的参数
- //storeMoney(20, 10, 100);
- int days = storeMoney(20, 10, 100);
- System.out.println("小明需要"+ days +"天才能存够100元!");
-
- //还可以传入别的参数,例如想让小明存够200元
- System.out.println("小名需要" + storeMoney(20, 10, 200) + "天才能存够200元!");
- }
- /*
- 构造一个方法,传入每天的零用钱,周一到周六的开销和存钱的目标,返回存够钱的天数!
- */
- public static int storeMoney(int allowance, int overHead, int target){
- int day = 1;
- int money = 0;
- int store = allowance - overHead;//计算周一到周六每天能存多少钱
-
- while(money < target){
- if(day % 7 == 0){//如果是周日,先把周日的零钱allowance存入再花去积蓄中的一半(所以这里存的是20,而不是10)
- money = (money + allowance) / 2;
- day++;
- }
- else{
- while(money < target){
- money = money + store;
- day++;
- }
- }
- }
-
- //System.out.println("小明需要"+day+"天能存够"+target+"元!");
- return day;
- }
- }
复制代码 |