题目
喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水,给20元,可以多少汽水(编程实现)。
解答
该题不难,小学数学题,解答如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int money = 0; //初始化金钱
int total = 0; //初始化所买的汽水总数
int empty = 0; //初始化空瓶数
scanf("%d", &money); //输入金钱数
total = money;
empty = money;
while (empty >= 2)
{
total += (empty / 2); //加上空瓶换的汽水数目
empty = empty / 2 + empty % 2; //计算剩余的空瓶数目
}
printf("%d", total);
return 0;
}
思考
写好程序,我们运行看看
![](https://img-blog.csdnimg.cn/img_convert/8d489a466c25e3c462fccdc10fbe4134.png)
![](https://img-blog.csdnimg.cn/img_convert/a479861108da79546d4185eb1d32c592.png)
![](https://img-blog.csdnimg.cn/img_convert/149bfccd9c6e9d6f939c226df321ca4a.png)
似乎,有什么规律
19=2*10-1
11=2*6-1
123=2*62-1
……
total = 2 * money - 1
我们找到了数学规律,那么我们的代码就可以改的更简单
#include <stdio.h>
#include <stdlib.h>
int main()
{
int money = 0;
int total = 0;
int empty = 0;
scanf("%d", &money);
total = 2 * money - 1;
printf("%d", total);
return 0;
}
当然,有一个小问题是当money = 0时,这种方案的计算结果是-1,显然不符合实际,只要稍微改一改。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int money = 0;
int total = 0;
int empty = 0;
scanf("%d", &money);
if (money > 0)
total = 2 * money - 1;
printf("%d", total);
return 0;
}
小结
可见,合理应用数学思维,要比直接去编代码要高效的多。