C语言二十四弹--喝汽水问题

C语言解决喝汽水问题

题目:喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水,给20元,可以喝多少汽水?

方法一、逐瓶购买法

思路:一瓶瓶的买 当空瓶有两个时,汽水数加1即可。

c 复制代码
#include <stdio.h>

int main()
{
	int bottle = 0;//瓶子
	int empty = 0;//空瓶子
	int money = 20;
	while (money > 0)//没钱就无法购买了~
	{
		money--;//每进入一次循环 钱会减少一块 瓶子数会增多一个
		bottle++;

		if (bottle % 2 == 0)//有偶数空瓶就会获得一个瓶子
		{
			bottle++;
		}
	}
	printf("%d",bottle);
	return 0;
}

方法二、一次性购买兑换法

思路:一次性把钱花光买汽水,然后会有一半的空瓶,再兑换汽水,然后又会有空瓶,再次兑换汽水。

c 复制代码
#include <stdio.h>

int main()
{
	int money = 20;
	int bottle = money;// 一次性购买完 汽水初始化就有20
	int empty = 20;//喝完空瓶也会有20
	while (empty > 1)//只要还有1个以上的空瓶子 就可以继续兑换汽水
	{
		bottle += empty / 2;//汽水数在原来基础上加上空瓶子的一半
		empty = empty / 2 + empty % 2;//喝完之后又会剩余空瓶,求到剩余空瓶数。
	}

	printf("%d",bottle);
	return 0;
}

方法三、公式法

思路:根据要求可以发现满足2 * money - 1,所以直接代入公式直接求即可

c 复制代码
#include <stdio.h>

int main()
{
	int money = 20;
	int bottle = 0;
	bottle = 2 * money - 1;
	printf("%d",bottle);
	return 0;
}
相关推荐
Hx_Ma161 天前
前台模块以及分页逻辑
java·开发语言
亓才孓1 天前
AspectJ和SpringAOP的区别
java·开发语言
大鹏说大话1 天前
破局单体瓶颈:SQLParser 解析器的分层架构重构实战
开发语言
tod1131 天前
C++ 核心知识点全解析(八)
开发语言·c++·面试经验
Ljwuhe1 天前
C++类与对象(上)
开发语言·c++
十启树1 天前
QGis开发环境部署
开发语言·gis·qgis
亚比囧1 天前
Java基础--面向对象(二)
java·开发语言
乐观勇敢坚强的老彭1 天前
c++寒假营day05
开发语言·c++·算法
枫叶丹41 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
重生之后端学习1 天前
74. 搜索二维矩阵
开发语言·数据结构·算法·职场和发展·深度优先