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;
}
相关推荐
码匠许师傅6 分钟前
【C++三方组件】mbedTLS:面向嵌入式的轻量 TLS
开发语言·c++
迪菲赫尔曼30 分钟前
【基础篇 12】把环境与源码接起来:检查 GPU,再安装服务器上的项目
运维·服务器·开发语言·人工智能·python·yolo·目标检测
2601_962885721 小时前
2026 Python 股票数据接口选型指南(横评 + 决策树)
开发语言·python·区块链
Evand J1 小时前
【PMSM例程4】PMSM电阻辨识与模型补偿EKF,MATLAB例程。附下载链接,包运行成功
开发语言·matlab·电机·ekf·卡尔曼·pmsm
王仔小奶1 小时前
Rust 正在接管金融圈?深度拆解一份高薪 FinTech 岗位 JD
开发语言·金融·rust
小王C语言1 小时前
Qt常用控件:多元素控件,纵向列表,表格控件,树状控件
开发语言·qt
fanruitian1 小时前
python 可视化 panda seaborn matplotlib.pyplot
开发语言·python·matplotlib
jnrjian2 小时前
delete file shell 让 AI 写脚本
服务器·开发语言
傅科摆 _ py2 小时前
DP,贪心,堆和栈,二分力扣复习
开发语言·python·算法
kiracrimson2 小时前
栈与队列容器:适配器、deque 与 priority_queue
开发语言·c++·适配器模式