每瓶汽水1元,两个空瓶可以置换一瓶汽水,现在有20元,最多能喝多少
瓶汽水?
分析:
首先,有20元,所以可以喝20瓶水(total = 20),有20个空瓶子。
20/2------------10(水)(total += 20)
bottles = 20/2 +20%2-------------(bottles = 10)
10/2---------------5(水)---------(total += 5)
bottles = 10/2 + 10%2----------- (bottles = 5)
5/2-----------------2(水)-----------(total += 2)
bottles = 5/2 +5%2--------------- (bottles = 3)
3/2-----------------1(水)--------(total += 1)
bottles = 3/2 +3%2----------------(bottles = 2)
2/2------------------1(水)--------(total += 1)
bottles -------------------------------1
以上用的是数学的算法,下面编程实现:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int main()
{
int total = 20;//初始条件-----20元----20瓶水
int bottles = 20;//20个空瓶子
while (bottles > 1)//当还有2个及以上的瓶子时,执行循环
{
total += bottles/2;
bottles = bottles/2 + bottles % 2;
}
printf("total = %d\nbottles = %d\n",total,bottles);
system("pause");
return 0;
}
但是,这道题如果放在实际生活中,或许可以得到40瓶水,因为如果
当只剩一瓶水时,你可以向店家借一瓶水,使之和你手中的空瓶构成
2个空瓶,这时你还可以换一瓶水,当喝完水后再把这个空瓶子还给
店家,是不是很机智呢,哈哈,如果你还有更好的方法,欢迎指教哦