来来来,做道题,一起防老年痴呆
![](https://images2015.cnblogs.com/blog/582383/201603/582383-20160323194927198-1381009813.jpg)
实现一:
include<stdio.h> include<stdlib.h> void exchangeOne(int money){ int alcol = 0; int bottle = 0; int lip = 0; while(1) { if(money >0){ money -= 2; alcol += 1; bottle += 1; lip += 1; } if(bottle >=2){ wine += 1; bottle -=2; lip += 1; } if(lip >= 4 ){ wine += 1; lip -= 4; bottle += 1; } if(money < 0){ if((lip < 4) && (bottle < 2){ break; } } } printf("一共兑换了%d瓶酒\n", alcol); } int main(){ int money = 10; exchangeOne(money); }
According to the first function :exchangeOne,it is obvious that the function is inefficient ,especailly when the money is too much , one time two yuan was subtracted from money which is not worthwile !
方案二。
#include<stdio.h> #include<stdlib.h> void exchangeTwo(int init_alcol){ int alcol = 0; int bottle = 0; int lip = 0;
alcol = init_alcol; bottle = init_alcol; lip = init_alcol; while(1) { alcol += bottle/2; //use bottle to exchange alcol lip += bottle/2; //one bottle of alcole, one lip . bottle = bottle%2 + bottle/2 ; alcol += lip/4; //use lip to exchange alcol lip = lip%4 + lip/4; bottle += lip/4 ;
if(lip < 4 && bottle < 2 ) { break; } } printf(" 一共兑换了%d瓶酒\n",alcol); } int main(){ int money = 10; exchangeTwo(money/2); //firstly ,use the money to buy alcol at the price of two yuan per bottle of alcol
}