Teaching myself Java, I reached an example problem that asks me to create a cash register program that will calculate the total change back to the customer in Dollars, Nickels, Quarters, Dimes, and pennies.
I worked out the user input but getting the correct sub-units is tricky part. For example: it's was easy to write the line of code that returned $1 dollar back if the cost was $4 and amount tendered was $5. But the trouble I am having is putting how many dimes and pennies needed in the correct field. ex2: total cost $4.62, tendered: $5, change: $0.38
System.out.print("Enter the sale amount: $ ");
double sale = user.nextDouble();
System.out.print("Enter the amount tendered by customer: $ ");
double tendered = user.nextDouble();
double totalChange = (tendered - sale);
System.out.printf("TOTAL CHANGE: $ %.2f\n", totalChange);
dollars = totalChange/1;
quarters = totalChange/25;
dimes = totalChange/10;
nickels = totalChange/5;
pennies = totalChange/1;
System.out.printf("DOLLARS: %.2f\n", dollars);
System.out.printf("QUARTERS: %.2f\n", quarters);
System.out.printf("DIMES: %.2f\n", dimes);
System.out.printf("NICKELS: %.2f\n", nickels);
System.out.printf("PENNIES: %.2f\n", pennies);
I don't need the answer (because I want to learn and teach myself), but just need some advice on how to go about doing so.
EDIT: What am I doing wrong with this algorithm:
dollars = totalChange/1;
dollars = (int)dollars;
dl = totalChange % 1;
quarters = dl/0.25;
q = quarters % 0.25;
quarters = (int)quarters;
dimes = q / .10;
d = dimes % .10;
nickels = d / .5;
n = nickels % .5;
pennies = n / .1;
n = pennies/ .1;