【C】练习:喝汽水问题

文章通过两种方法展示了如何使用C语言解决空瓶子换水的编程问题。第一种是递归实现,通过不断用空瓶子换取新水,直到无法再换。第二种方法利用等差数列,直接计算出总共能喝到的水量。两种方法都基于20元钱初始可买20瓶水,之后2个空瓶子可以换一瓶水的规则。
摘要由CSDN通过智能技术生成

自写代码(递归实现)

#include <stdio.h>
int empty_bottle(int a)
{
	if (a == 0)
	{
		return 0;
	}
	else
	{
		return 1 + empty_bottle(a - 1);
	}
}
int main()
{
	int n = 0;
	scanf("%d", &n);
	int ret = 0;
	ret = n + empty_bottle(n);
	printf("%d\n", ret);
	return 0;
}

参考代码

/*
思路:
1. 20元首先可以喝20瓶,此时手中有20个空瓶子
2. 两个空瓶子可以喝一瓶,喝完之后,空瓶子剩余:empty/2(两个空瓶子换的喝完后产生的瓶子) + empty%2(不够换的瓶子)
3. 如果瓶子个数超过1个,可以继续换,即重复2
*/
int main()
{
	int money = 0;
	int total = 0;
	int empty = 0;
	scanf("%d", &money);

	//方法1
	total = money;
	empty = money;
	while(empty>1)
	{
		total += empty/2;
		empty = empty/2+empty%2;
	}
	return 0;
}
 
 
// 方法二:按照上述喝水和用瓶子换的规则的话,可以发现,其实就是个等差数列:money*2-1
int main()
{
	int money = 0;
	int total = 0;
	int empty = 0;
 
	scanf("%d", &money);
	
	//方法2
	if(money <= 0)
	{
		total = 0;
	}
	else
	{
		total = money*2-1;
	}
	printf("total = %d\n", total);
 
 
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值