喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水, 给20元,可以多少汽水。

喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水, 
给20元,可以多少汽水。 

第一种方法:(非递归)

#include<stdio.h>
int main()
{
    int total = 0;        //瓶子数
    int kps = 0;          //钱数
    int ys = 0;
    printf("请输入钱数:");
    scanf("%d", &total); 
    kps = total;
    while (kps >= 1)
    {
        kps += ys;
        total += kps / 2;
        ys = kps % 2;
        kps /= 2;
    }
    printf("能换取 %d 瓶汽水\n", total);
    return 0;
}

第二种方法:(递归)

#include <stdio.h>
#include <stdlib.h>
int buy_sode(int n)
{
	static int flag = 0;
	if((n*2 + flag) < 2)
	{
		return 0;
	}
	if(0 == n%2)
	{
		return n + buy_sode(n/2);
	}
	else if((1 == n%2) && (0 == flag))
	{
		flag = 1;
		return n + buy_sode(n/2);
	}
	else if((1 == n%2) && (1 == flag))
	{
		flag = 0;
		return n + buy_sode(n/2 + 1);
	}
	return 0;
}

int main() 
{
    int money = 0;
    printf("请输入钱数:");
    scanf("%d", &money);
    printf("可以买 %d 瓶汽水\n", buy_sode(money));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/USA_AM_1966/article/details/83858371