0

Why is the last calculation printing out the wrong calculation. here is my code:

System.out.print("Enter total cost: ");

double totalCost = input.nextDouble();
System.out.print("The Customer has paid: ");
double customerAmount = input.nextDouble();

//Calculations
double changeOwed = customerAmount - totalCost;
System.out.println("Change owed: $"+(int)changeOwed);

int amountFifty = (int)changeOwed/50;
System.out.println("How many $50 notes = " +amountFifty);

int takeAway = (int)changeOwed - (amountFifty * 50);

int amount20 = takeAway / 20;
System.out.println("How many $20 notes = " +amount20);

int amount10 = (takeAway - amount20*20) / 10;
System.out.println("How many $10 notes = " +amount10);
enter code here
int amount5 = (takeAway - amount10*10) / 5;
System.out.println("How many $5 notes = " +amount5);

int amount2 = (takeAway - amount5*5) / 2;
System.out.println("How many $2 notes = " +amount2);

int amount1 = (takeAway - amount2*2) /1;
System.out.printl

n("How many $1 notes = " +amount1);
Sammy I.
  • 2,523
  • 4
  • 29
  • 49
Emmet1
  • 1
  • 1
    What's wrong with the last calculation? Can you edit your question to include your expected output and your actual output. – dave Feb 08 '20 at 01:01
  • Could you be more specific on what you're trying to do? What is the expected output here? What is showing up instead of the expected output? – Sammy I. Feb 08 '20 at 01:29
  • Do not use double for currency - see [here](https://stackoverflow.com/q/3730019/2670892) – greg-449 Feb 08 '20 at 14:35

1 Answers1

2

You are not keeping track of the change you have issued along the way correctly.

int takeAway = (int)changeOwed - (amountFifty * 50);

The line above correctly calculates what's left after you determine the number of $50 bills required. This means that:

int amount20 = takeAway / 20;
int amount10 = (takeAway - amount20*20) / 10;

correctly calculates the number of $10 and $20 bills.

int amount5 = (takeAway - amount10*10) / 5;

is incorrect because you do do not subtract the values of the $20 bills, only the $10 bills. You make a similar error calculating the $2, ie. you do not account for $20 and $10. The error compounds for the $1.

You could try something like:

    int amountFifty = changeOwed / 50;
    double takeAway = changeOwed - (amountFifty * 50);
    int amount20 = takeAway / 20;
    takeAway -= (amount20 * 20);
    int amount10 = takeAway / 10;
    takeAway -= (amount10 * 10);
    int amount5 = takeAway / 5;
    takeAway -= (amount5 * 5);
    int amount2 = takeAway / 2;
    takeAway -= (amount2 * 2);
    int amount1 = takeAway / 1;
dave
  • 11,641
  • 5
  • 47
  • 65