1

So, I'm supposed to write a program that takes a double value and returns the least amount of change. Everything seems to be okay but when I enter in double values such as "99.99" or "101.10" the answers are just a bit off.

public class Change {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double amount;
        double remainder;
        int tens = 0;
        int fives = 0;
        int toonies = 0;
        int loonies = 0;
        int quarters = 0;
        int dimes = 0;
        int nickels = 0;
        int pennies = 0;

        System.out.println("Enter in a double value:");
        amount = scanner.nextDouble();

        tens = (int) amount / 10;
        amount = amount % 10;

        fives = (int) amount / 5;
        amount = amount % 5;

        toonies = (int) amount / 2;
        amount = amount % 2;

        loonies = (int) amount / 1;
        amount = amount % 1;

        quarters = (int) (amount / 0.25);
        amount = amount % 0.25;

        dimes = (int) (amount / 0.10);
        amount = amount % 0.10;

        nickels = (int) (amount / 0.05);
        amount = amount % 0.05;

        pennies = (int) (amount / 0.01);
        amount = amount % 0.01;

        System.out.println("tens:" + tens);
        System.out.println("fives:" + fives);
        System.out.println("toonies:" + toonies);
        System.out.println("loonies:" + loonies);
        System.out.println("quarters:" + quarters);
        System.out.println("dimes: " + dimes);
        System.out.println("nickels: " + nickels);
        System.out.println("pennies: " + pennies);


    }
}

output for "99.99"

Enter in a double value:
99.99
tens:9
fives:1
toonies:2
loonies:0
quarters:3
dimes: 2
nickels: 0
pennies: 3

above, I am 1 penny short.

output for "101.10"

Enter in a double value:
101.10
tens:10
fives:0
toonies:0
loonies:1
quarters:0
dimes: 0
nickels: 1
pennies: 4

above, I am one penny short again

jayweezy
  • 81
  • 8
  • when I enter other double values in, I get the correct answers* – jayweezy Apr 03 '20 at 04:42
  • Why perform modulo to determine pennies? Keep decrementing `amount` with the appropriate values of tens, fives, deuces, singles, quarters, dimes and nickels. Whatever is left is the number of pennies (if you multiply by 100). – Elliott Frisch Apr 03 '20 at 04:57
  • @ElliottFrisch I just tried... if I enter "99.99" then after calculating nickels, I'm left with "0.03999999999999487." Now, if I multiply that by 100, I'm still left with "3.999..." pennies which will be rounded to 3 pennies and I'm still left with 1 penny short. – jayweezy Apr 03 '20 at 05:07
  • Not if you round with Math.ceil; or Math.round. Or even add 0.5 before you cast. Math is fun. – Elliott Frisch Apr 03 '20 at 05:25
  • @ElliottFrisch Math.round might work... hmmm thanks :) – jayweezy Apr 03 '20 at 07:18

0 Answers0