喝汽水问题:1瓶汽水1元。2个空瓶可以换1瓶汽水,给20元,可以买多少汽水 (7.19)

泪目!!!终于是自己完完整整写出的代码了,不翻资料也没看参考代码

(之前的要么和老师练习,要么找教材东拼西凑)

方法2:数学角度看bottle价值0.5 元,20元最多可换40bottle,由于喝到最后会剩一个bottle,故bottle=40-1=2*money-1。而soda=bottle,所以soda=2*money-1。

int main()
{
	int money = 0;
	int soda = 0;
	printf("input:");
	scanf("%d" ,&money);
	if (money < 0)
	{
		printf("soda=0\n");
	}
	else
	{
		printf("soda=%d\n", 2 * money - 1);
	}
	return 0;
}

方法1:思路如图所示:(还要考虑第三次循环和最后一个剩下的空瓶组成的汽水)

喝汽水问题:1瓶汽水1元。2个空瓶可以换1瓶汽水,给20元,可以买多少汽水 (7.19)_第1张图片

问题:

1.忘记让soda+soda1

2.缺少余数多出来的空瓶

int main()
{
	int money = 0;
	int soda = 0;
	int soda1 = 0;
	int bottle = 0;
	for ( money = 1; money <= 20; money++)
	{
		soda++;
		bottle++;
	}
	while (soda1 = bottle / 2)
	{
		bottle = soda1 + bottle % 2;
		soda += soda1;
	}
	printf("%d\n", soda);
	return 0;
}

这是第二版,又又又漏掉了5/2多出来的一瓶bottle+最后一瓶bottle=soda

int main()
{
	int money = 0;
	int soda = 0;
	int soda1 = 0;
	int bottle = 0;
	for ( money = 1; money <= 20; money++)
	{
		soda++;
		bottle++;
	}
	while (soda1 = bottle / 2)
	{
		bottle = soda1;
		soda += soda1;
	}
	printf("%d\n", soda);
	return 0;
}

下面是第一版,代码是错的,把20空瓶想成了10空瓶,也没有考虑到空瓶能继续转换成汽水的情况

int main()
{
	int money = 0;
	int soda = 0;
	int soda1 = 0;
	int bottle = 0;
	//money=soda;
	//soda=2*bottle;
	for ( money = 1; money <= 20; money++)
	{
		soda++;
		if (soda % 2 == 0)
		{
			bottle++;
		}
		if (bottle != 0 && bottle % 2 == 0)
		{
			soda1++;
			bottle = 0;
		}
	}
	printf("%d\n", soda+soda1);
	return 0;
}

你可能感兴趣的:(算法,c语言)