喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水,给20元,可以喝多少汽水
对于这道问题,我们可以把它推广到更普遍的情形:
喝汽水,1瓶汽水Onebot元,excange个空瓶可以换一瓶汽水,给money元,可以喝多少汽水,剩remain元?
- 首先,只有第一批汽水是购买得来,数量为total = money / Onebnot,此时我们剩余remain = money % Onebot。
- 所以,我们在进入兑换循环之前就已经拥有空瓶empty = total。
- 每次兑换,我们得到新瓶子Newbot = empty / excange,所以我们要将所有的新瓶子累加在total上,这将是我们可以喝到的汽水总瓶数。
- 但是每次空瓶不一定可以被完全兑换,所以每次兑换会剩下empty % excange个空瓶不能被兑换,这些剩余空瓶与本次兑换循环所得Newbot一起计入empty。
我们代码最终实现如下:
//Visual Studio 2022 17.11.5
//Debug x64
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
int money = 0;
int Onebot = 0;
int total = 0;
int excange = 0;
int remain = 0;
int empty = 0;
int Newbot = 0;
printf("你有多少钱?\n");
scanf("%d", &money);
printf("一瓶汽水多少钱?\n");
scanf("%d", &Onebot);
printf("几个空瓶可以换一瓶汽水?\n");
scanf("%d", &excange);
total = money / Onebot;
remain = money % Onebot;
printf("你剩了%d元\n", remain);
empty = total;
while (empty >= excange)
{
Newbot = empty / excange;
total += Newbot;
empty = empty % excange + Newbot;
}
printf("你可以喝%d瓶汽水\n", total);
return 0;
}