本帖最后由 黎志勇 于 2014-6-28 19:06 编辑
- public class BuyColaEvent {
- public static void main(String[] args) {
- buyCola(28);
- // buyCola(50);
- }
- public static void buyCola(int man) {// man为要喝可乐的人数
- // 买的数目,喝了的人数,空瓶数,瓶盖数
- int buyCount = 0, drinkedCount = 0, emptyBottle = 0, cap = 0;
- while (drinkedCount < man) {
- buyCount++;
- drinkedCount++;
- emptyBottle++;
- cap++;
- System.out.println("买第" + buyCount + "瓶,剩下" + emptyBottle + "个空瓶,"
- + cap + "个瓶盖,第" + drinkedCount + "人喝到可乐");
- while (emptyBottle >= 2 || cap >= 3) {
- if (emptyBottle >= 2) {
- emptyBottle = emptyBottle - 1; // 2空瓶兑换1可乐,得到1个空瓶,折合少了1空瓶
- drinkedCount++;
- cap++; // 喝完多一个瓶盖
- System.out.println("\t" + "2空瓶兑换1可乐,剩下" + emptyBottle
- + "个空瓶," + cap + "个瓶盖,第" + drinkedCount + "人喝到可乐");
- }
- if (cap >= 3) {
- cap = cap - 2; // 3瓶盖兑换1可乐,得到1个瓶盖,折合少了2个瓶盖
- drinkedCount++;
- emptyBottle++; // 喝完多一个空瓶
- System.out.println("\t" + "3瓶盖兑换1可乐,剩下" + emptyBottle
- + "个空瓶," + cap + "个瓶盖,第" + drinkedCount + "人喝到可乐");
- }
- }
- }
- System.out.println(man + "个人,需要买" + buyCount + "瓶");
- }
- }
复制代码 其实很简单,一瓶一瓶地买,凑够数就立即换,把这个过程用程序来表达出来就行。中间那些输出语句可以注释掉,我用来看过程的,剩下最后一个结果就行。
|