1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | //啤酒2元一瓶,四个瓶盖可换一瓶啤酒,2个空瓶也可换一瓶啤酒。10元最多可以喝多少瓶啤酒? public class beer { public static final int INITIAL_MONEY = 10, //题目说有10块钱 CAPS_FOR_BEER = 4, //题目说4个瓶盖可以换1瓶啤酒 BOTTLES_FOR_BEER = 2,//题目说2个瓶子可以换1瓶啤酒 BEER_PRICE = 2; //啤酒2块钱1瓶 public static void main(String[] args) { int drunk = 0, //最开始还没喝酒,所以0瓶酒被喝了 money = INITIAL_MONEY, //于是现在你有题目说的10块钱了 bottles = 0, //还没有瓶子 caps = 0; //还没有盖子 //如果还有钱买酒,或者还有足够的瓶盖,或者还有足够的瓶子,就继续去买酒 while (money >= BEER_PRICE || caps >= CAPS_FOR_BEER || bottles >= BOTTLES_FOR_BEER){ if (money >= BEER_PRICE){ //如果有足够的钱买酒 money -= BEER_PRICE; //扣掉酒钱 }else if(caps >= CAPS_FOR_BEER){ //如果有足够的瓶盖 caps -= CAPS_FOR_BEER; //扣掉盖子 }else if(bottles >= BOTTLES_FOR_BEER){ //如果有足够的瓶子 bottles -= BOTTLES_FOR_BEER; //扣掉瓶子 } //喝酒... drunk++; //多喝了1瓶酒 bottles++; //多了1个空瓶子 caps++; //多了一个盖子 } System.out.println("喝了" + drunk + "瓶\n" + "还剩下" + caps + "个盖子\n" + "还剩下" + bottles + "个瓶子\n" + "还剩下" + money + "块钱。"); /* 喝了15瓶 * 还剩下3个盖子 * 还剩下1个瓶子 * 还剩下0块钱。 */ } } |
数学老师:「…」