# C++ 問題 吃巧克力

Suppose we can buy a chocolate bar from the vending machine for \$1 each. Inside every chocolate bar is a coupon. We can redeem 7 coupons for one chocolate bar from the machine. We would like to know how many chocolate bars can be eaten, including those redeemed via coupon, if we have n dollars.For example, if we have 20 dollars then we can initially buy 20 chocolate bars. This gives us 20 coupons. We can redeem 14 coupons for 2 additional chocolate bars. These two additional chocolate bars have 2 more coupons, so we now have a total of 8 coupons when added to the six leftover from the original purchase. This gives us enough to redeem for one final chocolate bar. As a result we now have 23 chocolate bars and 2 leftover coupons.

Write a program that inputs the number of dollars and outputs how many chocolate bars you can collect after spending all your money and redeeming as many coupons as possible. Also output the number of leftover coupons. The easiest way to solve this problem is to use a loop.

### 1 個解答

• 最佳解答

這讓我想到之前有一個糖果問題...

題目簡單說就是

一元可以換一個巧克力棒，一個巧克力棒裡有一張優惠券

七張優惠券可以換一個巧克力棒。

輸入 n 元 可以換幾個巧克力棒 餘幾張優惠券。

以下方法請參考。

程式碼 :

#include <iostream>

using namespace std;

int main()

{

int money;

int chocolate=0;

int ticket=0;

int tmp;

cout << "money : "; cin >> money;

ticket = chocolate = money;

while(ticket >= 7)

{

tmp = ticket / 7;

chocolate += tmp;

ticket %= 7;

ticket += tmp;

}

cout << "chocolate : " << chocolate << endl;

cout << "ticket : " << ticket << endl;

system("pause");

return 0;

}

另一個方法 :

#include <stdio.h>

#include <stdlib.h>

int main()

{

int money;

int chocolate=0;

int ticket=0;

printf("money : "); scanf("%d",&money);

ticket = chocolate = money;

while(ticket >= 7)

{

ticket -= 7;

chocolate++;

ticket += 1;

}

printf("chocolate : %d\n",chocolate);

printf("ticket : %d\n",ticket);

system("pause");

return 0;

}