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;
}
相关推荐
临床数据科学和人工智能兴趣组3 小时前
在R语言中, 使用 as.factor() 函数转换数值型变量
开发语言·r语言
andyweike6 小时前
php笔记
开发语言·笔记·php
Circ.7 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
现任明教教主~8 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou1411369 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
码匠许师傅9 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
小小小小钰儿10 小时前
1.5-Python网络编程
开发语言·网络·python·web安全·计算机·网络安全
hiahiahia12310 小时前
实现完整 Tool Dispatcher
开发语言·前端