Jump to content

Event 1

- - - - -

  • Please log in to reply
29 replies to this topic

#1
Skippy

Skippy

    Programmer

  • Members
  • PipPipPipPip
  • 146 posts
For some background for this thread, please refer to http://forum.codecal...-community.html
Next Event : http://forum.codecal...-event-2-a.html

Title: Automated Cashier
By: Skippy
Influenced by: one of my jobs (lol)

Short Description: In this project you will create a program that calculates the amount of bills and coins as the change to some purchase by the user. The user will first input the amount of money he/she owes. Next he/she will input the amount of money tendered. The program will then compute the change owed and break that change owed into bills and coins. The program will then neatly output the change due, the amount of bills and coins returned to the customer ( i.e. 1x$20, 1x$10, 2x$5, 1x25c 4x1c), then exit.

Caution: The programmer must be aware of the customer entering too little change, or in the case of non reality console based cashier stuff, a negative amount, or even an amount not possible (i.e. 10.542... there is no thousandths of a dollar coin)

Caution: when converting from strings to floating point numbers to integers there may be a loss in precision if not coded carefully.
I came up a solution for this in C, so if you need help make sure you ask.

Advanced: The programmer is urged to add on additional useful features. The Advanced version and the Required version should be submitted separately though, so people can look at your required version without seeing a whole bunch of irrelevant code.

Requirements:
1) program asks user from the amount user owes
2) program asks user for the amount user tenders
3) program computes change
4) program outputs formatted change in the form of bills and coins

Sample output:
~/Desktop$ a.out

How much do you owe: 52.74

How much are you tendering: 60.00


$5 		x	1	=	5.00

$1 		x	2	=	2.00

25c		x	1	=	0.25

1c		x	1	=	0.01

----------------------------

change returned	=	7.26


~/Desktop$

And Please, Please, PLEASE make sure you use CODE tags.

Good luck!

Edited by Skippy, 21 January 2011 - 10:32 PM.


#2
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts
Alright I guess Ill be the first to put up some code! This is in C# Console:
static void Main(string[] args)
        {
            double amountDue = 0;
            double amountPaid = 0;
            double changeDue = 0;
            double totalChange = 0;

            double twentyBill = 0;
            double tenBill = 0;
            double fiveBill = 0;
            double oneBill = 0;
            double quarter = 0;
            double penny = 0;
    
            try
            {
                Console.Write("Amount Due: ");
                amountDue = Convert.ToDouble(String.Format("{0:0.00}", Convert.ToDouble(Console.ReadLine())));
            
                Console.Write("\nPayment Amount: ");
                amountPaid = Convert.ToDouble(String.Format("{0:0.00}", Convert.ToDouble(Console.ReadLine())));
                
                changeDue = (amountPaid - amountDue);
                totalChange = (amountPaid - amountDue);
            }
            catch
            {
                Console.WriteLine("Invalid Information");
            }

            
            
          
            if (changeDue >= 20.00)
            {
                for (int i = 0; i <= 999; i++)
                {
                    if (changeDue >= 20.00)
                    {
                        changeDue -= 20.00;
                        twentyBill++;
                    }

                    if (changeDue < 20.00)
                    {
                        break;
                    }

                } 
            }

            if (changeDue >= 10.00)
            {
                for (int i = 0; i <= 999; i++)
                {
                    if (changeDue >= 10.00)
                    {
                        changeDue -= 10.00;
                        tenBill++;
                    }

                    if (changeDue < 10.00)
                    {
                        break;
                    }

                } 
            }

            if (changeDue >= 5.00)
            {
                for (int i = 0; i <= 999; i++)
                {
                    if (changeDue >= 5.00)
                    {
                        changeDue -= 5.00;
                        fiveBill++;
                    }
                    else if (changeDue < 5.00)
                    {
                        break;
                    } 

                }
            }

            if (changeDue >= 1.00)
            {
                for (int i = 0; i <= 999; i++)
                {
                    if (changeDue >= 1.00)
                    {
                        changeDue -= 1;
                        oneBill++;
                    }
                    else if (changeDue < 1.00)
                    {
                        break;
                    }

                } 
            }

            if (changeDue >= 0.25)
            {
                for (int i = 0; i <= 999; i++)
                {
                    if (changeDue >= 0.25)
                    {
                        changeDue -= 0.25;
                        quarter++;
                    }
                    else if (changeDue < 0.25)
                    {
                        break;
                    }

                }
            }
            
            if (changeDue >= 0.01)
            {
                for (int i = 0; i <= 999; i++)
                {
                    if (changeDue+0.01 >= 0.01)
                    {
                        changeDue -= 0.01;
                        penny++;
                    }
                    else if (changeDue <= 0.00)
                    {
                        break;
                    }

                }
            }

            Console.Write("\nTotal Change Do: $" + totalChange + ", " + twentyBill + "x$20 " + tenBill + "x$10 " + fiveBill + "x$5 " + oneBill + "x$1, " + quarter + "x25c " + penny + "x1c");
            Console.ReadLine();
        }
Works well to the best of my knowledge.

EDIT: Great idea Luth, here's a screen shot of mine as well.
Attached File  CC_Changer.png   26.85K   61 downloads

~ Committed. :)

Edited by CommittedC0der, 17 January 2011 - 10:01 PM.

A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.

#3
LuthfiHakim

LuthfiHakim

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 763 posts
Here is my code (Delphi/Pascal). Please note that although Skippy explicitly said that the programmer must pay attention to some possible "weird" situations, but I decided not to incorporate such tests/protections in order to make the code easier to read. Of course such things must be implemented in real world applications.

So here it goes.

program ChangeCalc;


{$APPTYPE CONSOLE}


uses

  SysUtils,

  Math;


type

  TChangeType = (ct20, ct10, ct5, ct1, ct25c, ct1c);


const

  DIVIDERS: array[TChangeType] of Integer =

    (2000, 1000, 500, 100, 25, 1);


  LABELS: array[TChangeType] of string =

    ('$20', '$10', '$5', '$1', '25c', '1c');


  INFOLINE = '%s x %d = %f';


var

  vPaid  : Integer;

  vDue   : Integer;

  vTmp   : Integer;

  vChange: Double;

  vCount : Integer;

  S      : string;

  i      : TChangeType;

begin

  Writeln('Welcome');

  Writeln('');

  Write('How much do you owe: ');

  ReadLn(S);

  vDue := Floor(StrToFloat(S) * 100);

  Write('How much are you tendering: ');

  ReadLn(S);

  vPaid := Floor(StrToFloat(S) * 100);

  Writeln('');


  vTmp := vPaid - vDue;

  vChange := vTmp / 100;


  if vTmp > 0 then

    for i := Low(TChangeType) to High(TChangeType) do

    begin

      vCount := vTmp div DIVIDERS[i];

      if vCount > 0 then

      begin

        WriteLn(Format(INFOLINE, [LABELS[i], vCount, (vCount * DIVIDERS[i])/100]));

        vTmp := vTmp mod DIVIDERS[i];

      end;

    end;

  WriteLn('---------------------------------------');

  WriteLn(Format('Change returned: %f', [vChange]));

  Readln;

end.


And here is the screenshot when it's in action.

Attached File  ScrShot01.png   10.87K   38 downloads

#4
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
In my mental state I managed to write something that resembles 90's ANSI C. Here:
#include <stdio.h>
#include <math.h>

int toCent(float);
float toDollar(int);
void setChange(int);

typedef struct {
  char* m_iStrName;
  int m_iValueCents;
  int m_iCoins;
} COINS;

COINS arrCoins[] =
{
  { "$20", 2000, 0 },
  { "$10", 1000, 0 },
  { "$5", 500, 0 },
  { "$1", 100, 0 },
  { "25c", 25, 0 },
  { "10c", 10, 0},
  { "5c", 5, 0 },
  { "1c", 1, 0 }
};

int main (int argc, char* argv[]) {
  float owe, tender;
  int i;

  input:
  printf("How much do you owe: ");
  scanf("%f", &owe);
  printf("How much are you tendering: ");
  scanf("%f", &tender);

  if((tender - owe) < 0) {
      fprintf(stderr, "\nError: You owe more than value put.\n");
      goto input;
  }

  int change = toCent(tender - owe);
  setChange(change);
  int iCoinSlot = sizeof (arrCoins) / sizeof (arrCoins[0]);
  COINS* pCoinSlot = arrCoins;

  for(i=0; i < iCoinSlot; i++, pCoinSlot++) {
    if(pCoinSlot->m_iCoins) {
      printf("\n%s\tx\t%d\t=\t%0.2f",
        pCoinSlot->m_iStrName,
        pCoinSlot->m_iCoins,
        (float)(pCoinSlot->m_iValueCents * pCoinSlot->m_iCoins) / 100);
    }
  }
  printf("\n----------------------------");
  printf("\nChange returned: $%0.2f", toDollar(change));
  return 0;
}

int toCent(float dollars) {
  return round(dollars * 100);
}
float toDollar(int cents) {
  return (float)cents / 100;
}

void setChange(int iCents) {
  int iCoinSlot = sizeof(arrCoins) / sizeof(arrCoins[0]);
  COINS* pCoinSlot = arrCoins;
  int i;
  for (i=0; (i < iCoinSlot) && (iCents > 0); i++, pCoinSlot++) {
    if (iCents < pCoinSlot->m_iValueCents) {
      continue;
    }
    pCoinSlot->m_iCoins = iCents / pCoinSlot->m_iValueCents;
    iCents %= pCoinSlot->m_iValueCents;
  }
}
Output (shows satisfying erroneous input)
terminal$./a.out
How much do you owe: 52.74
How much are you tendering: -2

Error: You owe more than value put.
How much do you owe: 52.74
How much are you tendering: 60.00

$5    x    1    =    5.00
$1    x    2    =    2.00
25c   x    1    =    0.25
1c    x    1    =    0.01
----------------------------
Change returned: $7.26

Edited by Alexander, 19 January 2011 - 04:02 AM.

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#5
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
-Java-

Okay, it turned out sort of big.
I wanted to validate input by doing if( input%0.01 == 0) ...
but doubles were being annoying as 52.74%0.01 = x.yzabd E-18 instead of just being 0.
... So i made a currency class which works with 2 integers.
No idea what the english words are for the part that comes before the comma, and after. So I named them bigMoney (before comma) and smallMoney(after comma)

Currency class:

package event.event1;


public class Currency implements Comparable{

    private int bigMoney;

    private int smallMoney;


    public Currency(int bigMoney, int smallMoney) {

        if (smallMoney > 100) {

            this.smallMoney = smallMoney % 100;

        } else {

            this.smallMoney = smallMoney;

        }

        this.bigMoney = bigMoney + (smallMoney / 100);

    }


    public Currency(String bigMoney, String smallMoney) {

        this.bigMoney = Integer.parseInt(bigMoney);

        this.smallMoney = Integer.parseInt(smallMoney);

    }


    public boolean isValid() {

        return (smallMoney < 100) && (smallMoney >= 0) && bigMoney>=0;

    }


    public Currency minus(Currency debt) {

        int resultSmall = smallMoney - debt.smallMoney;

        int resultBig = bigMoney - debt.bigMoney;

        if (resultSmall < 0) {

            resultSmall += 100;

            resultBig--;

        }


        return new Currency(resultBig, resultSmall);

    }


    public int divide(Currency divisor) {

        return (bigMoney * 100 + smallMoney) / (divisor.bigMoney * 100 + divisor.smallMoney);

    }


    public Currency multiply(int value) {

        bigMoney *= value;

        smallMoney *= value;

        if (smallMoney > 100) {

            bigMoney += (smallMoney / 100);

            smallMoney %= 100;

        }


        return new Currency(bigMoney, smallMoney);

    }


    public int getBigMoney() {

        return bigMoney;

    }


    public int getSmallMoney() {

        return smallMoney;

    }


    @Override

    public String toString() {

        return bigMoney + "." + smallMoney;

    }


    public int compareTo(Object o) {

        Currency other = (Currency) o;

        int total = bigMoney*100 + smallMoney;

        int otherTotal = other.bigMoney*100 + other.smallMoney;

        return otherTotal - total;

    }

}


The actual class

package event.event1;


import java.util.Arrays;

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;


public class AutomatedCashier {

    private Currency debt;

    private Currency offer;

    private Map<Currency, Integer> changeMoney;


    public AutomatedCashier() {

        changeMoney = new HashMap<Currency, Integer>();

        changeMoney.put(new Currency(50, 0), 0);

        changeMoney.put(new Currency(20, 0), 0);

        changeMoney.put(new Currency(10, 0), 0);

        changeMoney.put(new Currency(5, 0), 0);

        changeMoney.put(new Currency(1, 0), 0);

        changeMoney.put(new Currency(0, 25), 0);

        changeMoney.put(new Currency(0, 1), 0);

    }


    public void run() {

        do {

            debt = null;

            offer = null;

            askInput();

        } while (!validInput());


        calculateChange();

        printResult();

    }


    private boolean validInput() {

        Currency change = offer.minus(debt);

        return change.isValid();

    }


    private void askInput() {

        Scanner scanner = new Scanner(System.in);


        while (debt == null || !debt.isValid()) {

            System.out.println("How much do you owe: ");

            String[] input = scanner.nextLine().split("[,.]");

            debt = new Currency(input[0], input[1]);


        }


        while (offer == null || !offer.isValid() && offer.minus(debt).isValid()) {

            System.out.println("How much are you tendering: ");

            String[] input = scanner.nextLine().split("[,.]");

            offer = new Currency(input[0], input[1]);

            Currency change = offer.minus(debt);

        }

    }


    private void calculateChange() {

        Currency change = offer.minus(debt);

        Object[] keys = changeMoney.keySet().toArray();

        Arrays.sort(keys);

        for (Object val : keys) {

            Currency key = (Currency) val;

            int value = change.divide(key);

            changeMoney.put(key, value);

            change = change.minus(new Currency(key.getBigMoney() * value, key.getSmallMoney() * value));

        }


    }


    private void printResult() {

        Object[] keys = changeMoney.keySet().toArray();

        Arrays.sort(keys);

        for (Object val : keys) {

            Currency value = (Currency) val;

            int amount = changeMoney.get(value);

            String money = value.getBigMoney() == 0 ? value.getSmallMoney() + "c" : "$" + value.getBigMoney();

            System.out.printf("%-10s x %5d      = %10s\n", money, amount, value.multiply(amount));

        }

        System.out.println("-------------------------");

        System.out.printf("Change returned = %7s", offer.minus(debt));

    }


    public static void main(String[] args) {

        AutomatedCashier cashier = new AutomatedCashier();

        cashier.run();

    }

}

Yup.. a lot of code.
Posted Image

#6
LuthfiHakim

LuthfiHakim

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 763 posts
Wow! Nice codes!

wim DC said:

-Java-
Okay, it turned out sort of big.
I wanted to validate input by doing if( input%0.01 == 0) ...
but doubles were being annoying as 52.74%0.01 = x.yzabd E-18 instead of just being 0.

That's why in my code I "cast" them first to integer, since the smallest change we are dealing with is 1 cent. So I believe it's safe to do the main calculations in terms of cents (by multiplying with 100).

#7
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java

LuthfiHakim said:

Wow! Nice codes!



That's why in my code I "cast" them first to integer, since the smallest change we are dealing with is 1 cent. So I believe it's safe to do the main calculations in terms of cents (by multiplying with 100).
Now there's an idea ^^
Lemme try that.

result:

public class AutomatedCashier {

    private int debt;

    private int offer;

    private Map<Integer, Integer> changeMoney;


   [COLOR="blue"][B] public AutomatedCashier() {[/B][/COLOR]

        changeMoney = new HashMap<Integer, Integer>();

        changeMoney.put(5000, 0);

        changeMoney.put(2000, 0);

        changeMoney.put(1000, 0);

        changeMoney.put(500, 0);

        changeMoney.put(100, 0);

        changeMoney.put(25, 0);

        changeMoney.put(1, 0);

    }


   [COLOR="blue"][B] public void run() {[/B][/COLOR]

        do {

            askInput();

        } while (!validInput());

        calculateChange();

        printResult();

    }


    [COLOR="blue"][B]private boolean validInput() {[/B][/COLOR]

        return offer - debt >= 0;

    }


    [COLOR="blue"][B]private void askInput() {[/B][/COLOR]

        Scanner scanner = new Scanner(System.in);


        System.out.println("How much do you owe: ");

        debt = (int) (100 * scanner.nextDouble());


        System.out.println("How much are you tendering: ");

        offer = (int) (100 * scanner.nextDouble());

    }


    [COLOR="blue"][B]private void calculateChange() {[/B][/COLOR]

        int change = offer - debt;

        Object[] keys = changeMoney.keySet().toArray();

        Arrays.sort(keys);

        for (int i = keys.length - 1; i >= 0; i--) {

            int key = (Integer) keys[i];

            int value = change / key;

            changeMoney.put(key, value);

            change -= value * key;

        }

    }


    [COLOR="blue"][B]private void printResult() {[/B][/COLOR]

        Object[] keys = changeMoney.keySet().toArray();

        Arrays.sort(keys);

        for (int i = keys.length - 1; i >= 0; i--) {

            int value = (Integer) keys[i];

            int amount = changeMoney.get(value);

            System.out.printf("%-10s x %5d      =  %.2f\n", getMoneyString(value), amount, value * amount / 100.0);

        }

        System.out.println("-------------------------");

        System.out.printf("Change returned         =  %.2f", (offer - debt) / 100.0);

    }


    [COLOR="blue"][B]private String getMoneyString(int i) {[/B][/COLOR]

        if (i % 100 == 0) {

            return "$" + i / 100;

        } else {

            return i + "c";

        }

    }


    [COLOR="#006400"][B]public static void main(String[] args) {[/B][/COLOR]

        AutomatedCashier cashier = new AutomatedCashier();

        cashier.run();

    }

}



#8
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
Ah - Nicer result, Wim DC, If you browse over mine you will notice how it is a bit similar. Keep up the good work guys!
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#9
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
  • Location:New York, NY
Too lazy to do error checking.
#include <stdio.h>

#include <math.h>


int main(void)

{


  double z, y, x[10] = {100, 50, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01};


  printf("How much do you owe: ");

  scanf("%lf", &y);

  printf("How much are you tendering: ");

  scanf("%lf", &z);


  float diff = z - y;

  printf("Change returned: %4.2f\t\n", diff);


  int i, temp;

  for(i = 0; i < 10; i++) {

    if((temp = floor(diff / x[i])) > 0) {

      diff -= (temp * x[i]);

      printf("%d * %4.2f\t=\t%4.2f\n", temp, x[i], x[i]*temp);

    }

  }

  return 0;


}

{~} > cc a.c -lm

{~} > ./a.out

How much do you owe: 52.74

How much are you tendering: 60.00

Change returned: 7.26

1 * 5.00        =       5.00

2 * 1.00        =       2.00

1 * 0.25        =       0.25

1 * 0.01        =       0.01


#10
Skippy

Skippy

    Programmer

  • Members
  • PipPipPipPip
  • 146 posts
One thing I like about the code everyone is posting is that the indentation is all nice, and bracket usage is consistent. It makes it easy to read, and it's just an overall good habit to form.

@LuthfiHakim
I didn't build the source, but it's really interesting to see that code, I haven't seen many programs written in Delphi.
What other languages do you know?

@Alexander
I like it lol. Relatively small source that passes all the tests I threw at it.

@wim DC
Took me a few moments to figure out why the code in your second post wasn't working... forgot the imports lol. I should have checked, but I was looking at the first source and it had the imports.. so I was confused haha,
Anyways good job, works good.

John,
By far the shortest code so far, but it does the job

I did try it on a few different values though...

$ a.out

How much do you owe: 0

How much are you tendering: 99.99

Change returned: 99.99	

1 * 50.00	=	50.00

2 * 20.00	=	40.00

1 * 5.00	=	5.00

4 * 1.00	=	4.00

3 * 0.25	=	0.75

2 * 0.10	=	0.20

3 * 0.01	=	0.03

$ 

This type of thing was happening to my code too with the penny truncation. ( notice how its only 3 pennies, so the customer only got 99.98 back ).
See if you can find a way around it, I want to see what you come up with and compare it with what I came up with. I'll post my code when your new one is up.

Other than that, good job everyone. Glad to see so many people participate.
I think this one was a little bit to easy, but at the same time we aren't getting as many people as I'd like, do you guys think the next one should be easier to see if more people participate?

#11
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
  • Location:New York, NY
I suppose my immediate solution would be to multiply everything by 100 and simply deal with integer precision instead of floating point precision.

#12
Skippy

Skippy

    Programmer

  • Members
  • PipPipPipPip
  • 146 posts
I see, that is actually a good idea. Many people have done this in their source posted previously, so I don't expect you to repeat the idea.

I wrote the code before any of you guys did, so my code didn't use that more efficient method (didn't want to cheat lol)

Here is mine, broken up into two pieces

Main.cpp
#include <stdio.h>

#include <iostream>

#include <math.h>

#include "ChangeMaker.hpp"


int main( int argc, char** argv )

{

	using namespace std;

	

	double owed = -1.0;

	double tendered = -1.0;

	double epsilon = 0.0050; // has to be right upto one cent (rounded)

	

	// make sure input is within <epsilon> of 0.00 or greater than 0.00

	while( true )

	{

		cout << "Money owed: ";

		cin >> owed;

		if ( !(owed > 0.0 || fabs(owed) < epsilon) )

			cout << "ERROR: Illegal ammount.\n\n";

		else 

			break;

	}

	

	// make sure tendered is within <epsilon> of owed or greater than owed

	while ( true )

	{

		cout << "Money tendered: ";

		cin >> tendered;

		if ( !( tendered > owed || fabs( tendered - owed ) < epsilon) )

			cout << "ERROR: Amount tendered must be >= amount owed.\n\n";

		else

			break;

	}

	

	ChangeHolder change;

	

	ChangeMaker::MakeChange( tendered - owed, change );

	

	if ( change.bill_one_hundred )

		printf("100.00\t%4d\t= %9.2f\n", change.bill_one_hundred, change.bill_one_hundred * 100.0f);

	if ( change.bill_fifty )

		printf(" 50.00\t%4d\t= %9.2f\n", change.bill_fifty, change.bill_fifty * 50.0f);

	if ( change.bill_twenty )

		printf(" 20.00\t%4d\t= %9.2f\n", change.bill_twenty, change.bill_twenty * 20.0f);

	if ( change.bill_ten )

		printf(" 10.00\t%4d\t= %9.2f\n", change.bill_ten, change.bill_ten * 10.0f);

	if ( change.bill_five )

		printf("  5.00\t%4d\t= %9.2f\n", change.bill_five, change.bill_five * 5.0f);

	if ( change.bill_one )

		printf("  1.00\t%4d\t= %9.2f\n", change.bill_one, change.bill_one * 5.0f);

	if ( change.coin_quarter )

		printf("  0.25\t%4d\t= %9.2f\n", change.coin_quarter, change.coin_quarter * 0.25f);

	if ( change.coin_dime )

		printf("  0.10\t%4d\t= %9.2f\n", change.coin_dime, change.coin_dime * 0.10f);

	if ( change.coin_nickel)

		printf("  0.05\t%4d\t= %9.2f\n", change.coin_nickel, change.coin_nickel * 0.05f);

	if ( change.coin_penny )

		printf("  0.01\t%4d\t= %9.2f\n", change.coin_penny, change.coin_penny * 0.01f);

	

	printf("change\t\t= %9.2f\n", \

		change.bill_one_hundred * 100 + change.bill_fifty * 50 + change.bill_twenty * 20 + change.bill_ten * 10 + change.bill_five * 5 + change.bill_one * 1 \

		+

		(change.coin_quarter * 0.25) + (change.coin_dime * 0.10) + (change.coin_nickel * 0.05) + (change.coin_penny * 0.01) );

	

	return 0;

	

}

ChangeMaker.hpp:
#ifndef _CHANGEMAKER_H_

#define _CHANGEMAKER_H_


#include <string.h>

#include <math.h>


struct ChangeHolder{

	unsigned int bill_one_hundred;

	unsigned int bill_fifty;

	unsigned int bill_twenty;

	unsigned int bill_ten;

	unsigned int bill_five;

	unsigned int bill_one;

	unsigned int coin_quarter;

	unsigned int coin_dime;

	unsigned int coin_nickel;

	unsigned int coin_penny;

};


class ChangeMaker{


	public:

	static const int ERROR_NEGATIVE_CHANGE;

	static const int OK;

	static int MakeChange( double change, ChangeHolder & changeHolder );

	static void MakeChange( unsigned int dollars, unsigned int cents, ChangeHolder & changeHolder );

	static void FindPartIn( unsigned int & count, unsigned int denominator, unsigned int & numerator );

};


const int ChangeMaker::ERROR_NEGATIVE_CHANGE = -1;

const int ChangeMaker::OK = 0;


int ChangeMaker::MakeChange( double change, ChangeHolder & changeHolder )

{

	double epsilon = 0.0050;

	unsigned int dollars;

	unsigned int cents;

	double dollarsDouble;

	double centsDouble;

	

	if( !( change > 0.0 || fabs( change ) < fabs ( epsilon ) ) )

		return ChangeMaker::ERROR_NEGATIVE_CHANGE;

	

	centsDouble = (100.0 * modf( change, & dollarsDouble ));

	cents = (unsigned int) centsDouble;

	

	// takes care of truncation when converting double to int

	if( (centsDouble - cents) > epsilon)

		cents++;

	

	dollars = (unsigned int)(dollarsDouble);

	

	ChangeMaker::MakeChange( dollars, cents, changeHolder );

	

	return ChangeMaker::OK;

}

void ChangeMaker::FindPartIn( unsigned int & count, unsigned int denominator, unsigned int & numerator ){

	count = numerator / denominator ;

	numerator -= denominator * count;

}

void ChangeMaker::MakeChange( unsigned int dollars, unsigned int cents, ChangeHolder & changeHolder )

{

	

	ChangeMaker::FindPartIn( changeHolder.bill_one_hundred, 100, dollars );

	ChangeMaker::FindPartIn( changeHolder.bill_fifty, 50, dollars );

	ChangeMaker::FindPartIn( changeHolder.bill_twenty, 20, dollars );

	ChangeMaker::FindPartIn( changeHolder.bill_ten, 10, dollars );

	ChangeMaker::FindPartIn( changeHolder.bill_five, 5, dollars );

	ChangeMaker::FindPartIn( changeHolder.bill_one, 1, dollars );

	ChangeMaker::FindPartIn( changeHolder.coin_quarter, 25, cents );

	ChangeMaker::FindPartIn( changeHolder.coin_dime, 10, cents );

	ChangeMaker::FindPartIn( changeHolder.coin_nickel, 5, cents );

	changeHolder.coin_penny = cents;

}


#endif

output:
$ a.out

Money owed: 87.61

Money tendered: 87.604

ERROR: Amount tendered must be >= amount owed.


Money tendered: 100

 10.00	   1	=     10.00

  1.00	   2	=     10.00

  0.25	   1	=      0.25

  0.10	   1	=      0.10

  0.01	   4	=      0.04

change		=     12.39

$ 






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users