喝汽水问题.

喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水,
给20元,可以多少汽水。
编程实现。
39瓶.
面试情况下还可以借一瓶变为40瓶

#include <stdio.h>
#include <stdlib.h>
int main() {
	int money = 20;
	int bottle = money;
	int sum = money;
	while (bottle >=2 ) {
		sum += bottle / 2;
		bottle = bottle / 2 + bottle % 2;
	}
	printf("你可以喝%d瓶!\n",sum);
	system("pause");
	return 0;
}

升级版:华为面试题.
一个人买汽水,一块钱一瓶汽水,三个瓶盖可以换一瓶汽水,两个空瓶可以换一瓶汽水
问20块钱可以买多少汽水?
注意:使用递归

#include <stdio.h>
#include <stdlib.h>
int Soda(int drinks, int caps, int bottles) {
	caps %= 3;  bottles %= 2;
	caps += drinks; bottles += drinks;
	if (caps < 3 && bottles < 2 && drinks < 1) {
		return drinks;
	}
	else {
		return Soda(caps / 3 + bottles / 2, caps, bottles) + drinks;
	}
}
int main() {
	Soda(20, 0, 0);
	printf("你可以喝%d瓶!\n", Soda(20, 0, 0));
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Lange_Taylor/article/details/89223402