0

This is a problem that wants me to read a double value and determine the fewest number of bills and coin needed to represent the amount.

I'm getting a weird result. I put 5.05 as the moneytotal, and I'm getting 4 pennies when it should be 1 nickel.

I think its a rounding issue but I can't see how to change it when it the problem states to use double.

        Scanner scan=new Scanner(System.in);

        double moneytotal, ten, five, one, quarters, dimes, nickels,  pennies;


        System.out.println("Input number!");
        moneytotal=scan.nextDouble();

        ten= moneytotal % 10;
        System.out.println((moneytotal -ten)/10 + " Ten Dollar 
        Bills.");

        five=ten% 5;
        System.out.println(((ten - five)/5) + " Five Dollar Bills.");

        one = five % 1;
        System.out.println((five - one) + " One Dollar Bills.");

        quarters = one % 0.25;
        System.out.println(((one - quarters)*4) + " Quarters.");

        dimes= quarters % 0.10;
        System.out.println(((quarters - dimes)*10) + " Dimes.");

        nickels=dimes % 0.05;
        System.out.println(((dimes - nickels)*20) + " Nickels.");

        pennies=nickels % 0.01;
        System.out.println(((nickels - pennies) * 100)+ " Pennies.");

Actual result:

input > 5.05

5 Ten Dollar bills.
0 5 Dollar bills.
0 1 dollar bills.
0 quarters.
0 dimes.
0 nickels.
4 pennies.
acarlstein
  • 1,799
  • 2
  • 13
  • 21

1 Answers1

0

Calc it as int not double because you can meet the problem regarding of the type changed. In your code, monytotal % 10 is not 0.5 because 10 is int and % is not good for double. I think the result would be different by language.

Anyway, There is more perfect way as following:

int moneytotaln = moneytotal * 100

ten= moneytotaln % 1000;
System.out.println((moneytotaln -ten)/1000 + " Ten Dollar 
Bills.");
// ...
yaho cho
  • 1,779
  • 1
  • 7
  • 19
  • Thanks a bunch Mr. Cho! This helped me a ton! Also I never knew about java numbers not being exact so that using decimals isn't always accurate. Doing this got my code to work as intended! – Jessey Bland May 04 '19 at 04:30