实现一:
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瓶酒 ", 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瓶酒 ",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
}