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;
}
相关推荐
en.en..1 小时前
volatile 完整深度教程(C 代码 + 带注释 ARM 汇编 + 硬件中断原理 + 分步运行时序)
c语言·汇编·arm开发
小oo呆1 小时前
【学习心得】Python函数参数中的两个特殊分隔符
开发语言·python
x10n91 小时前
微软 VC++ 运行库合集VCRedistPack
开发语言·c++·microsoft·vc++运行库·dll报错
qz_Serene1 小时前
C++:string(底层,常用接口,具体题目,模拟实现)
开发语言·c++
NiceBlueChai1 小时前
Qt 跨线程传递多容器嵌套结构:一次 Release 实测
开发语言·qt
念何架构之路1 小时前
go-grpc逻辑架构图
开发语言·后端·golang
SEO_juper1 小时前
AI 爬虫 robots.txt 检查工具:你的站是不是把 AI 挡在门外了
开发语言·人工智能·爬虫·python·外贸独立站
木圭的AI时代指南2 小时前
实测 MiniMax M3.1 Flash:同一道 Three.js 大题,两个 agent 差出 4.6 倍
开发语言·javascript·ecmascript
星恒讯工业路由器2 小时前
工业路由器在中小 IoT 场景的选型与适配实践:从标准品到定制化的技术路径
开发语言·网络·物联网·php·工业路由器选型·工业网关odm·链路冗余切换