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 分钟前
go的interface接口底层实现
开发语言·后端·golang
小屁孩大帅-杨一凡14 分钟前
一个简单点的js的h5页面实现地铁快跑的小游戏
开发语言·前端·javascript·css·html
顾子茵23 分钟前
c++从入门到精通(四)--动态内存,模板与泛型编程
java·开发语言·c++
邹诗钰-电子信息工程28 分钟前
嵌入式自学第二十二天(5.15)
c语言
电信2301杨臣39 分钟前
QT---信号与槽
开发语言·qt
明月看潮生1 小时前
青少年编程与数学 02-019 Rust 编程基础 07课题、字符串
开发语言·青少年编程·rust·编程与数学
抽风的雨6101 小时前
【python基础知识】Day26 函数
开发语言·python
编程有点难1 小时前
Python训练打卡Day22
开发语言·python·机器学习
咕噜咕噜啦啦2 小时前
Python爬虫入门
开发语言·爬虫·python
dubochao_xinxi2 小时前
✅ TensorRT Python 安装精简流程(适用于 Ubuntu 20.04+)
开发语言·python·ubuntu