码迷,mamicode.com
首页 > 其他好文 > 详细

Change maker problem-找零(1-99美分)

时间:2014-08-31 18:48:19      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:change maker problem-找零(1-99美分)

Change maker problem-找零(1-99美分),允许重复计算:

//Change maker problem-找零(1-99美分)
#include<iostream>
using namespace std;

void compute_coins(int coin_value,int& number,int& amount_left);

int main()
{
    int cents,number[2],amount_left;
    char ans;
    
    do{
        cout<<"Enter the (1-99)cents:\n";
        cin>>cents;
        number[0]=number[1]=number[2] = {0};
        amount_left = cents;
        while(amount_left > 0)
            {
                if(amount_left >= 25)
                    {
                        compute_coins(25,number[0],amount_left);   
                        compute_coins(10,number[1],amount_left);
                        compute_coins(1,number[2],amount_left);
                    }
                else if(amount_left >= 10 && amount_left < 25)
                    {
                        compute_coins(10,number[1],amount_left);
                        compute_coins(1,number[2],amount_left);
                    }
                else if(amount_left >= 1 && amount_left < 10)
                    compute_coins(1,number[2],amount_left);
                
            }
        cout<<cents<<" cents can be given as "<<endl
            <<number[0]<<" quarter(s) "<<number[1]<<" dime(s) and "<<number[2]<<" penny(pennies)"<<endl;
        
        cout<<"Do you want again?";
        cin>>ans;
    }while(‘y‘ == ans || ‘Y‘ == ans);
}

void compute_coins(int coin_value,int& number,int& amount_left)
{
    switch(coin_value)
    {
        case 25:
            number = amount_left/25;
            amount_left = amount_left % coin_value;
            break;
        case 10:
            number = amount_left/10;
            amount_left = amount_left % coin_value;
            break;
        case 1:
            number = amount_left/1;
            amount_left = amount_left % coin_value;
            break;
        default:
            cout<<"ERROR!";
    }
}

结果:

Enter the (1-99)cents:
86
86 cents can be given as 
3 quarter(s) 1 dime(s) and 1 penny(pennies)
Do you want again?y
Enter the (1-99)cents:
25
25 cents can be given as 
1 quarter(s) 0 dime(s) and 0 penny(pennies)
Do you want again?y
Enter the (1-99)cents:
10
10 cents can be given as 
0 quarter(s) 1 dime(s) and 0 penny(pennies)
Do you want again?y
Enter the (1-99)cents:
1
1 cents can be given as 
0 quarter(s) 0 dime(s) and 1 penny(pennies)
Do you want again?


Change maker problem-找零(1-99美分)

标签:change maker problem-找零(1-99美分)

原文地址:http://9320314.blog.51cto.com/9310314/1547125

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!