Question:
I'm looking for a java program that can give the minimum change for a given amount in US currency.
Answer:
See example
Code:
import java.util.*; import java.math.*; public class MakeChange { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // example: 39.99 System.out.print("Enter total amount: "); double amount = sc.nextDouble(); // Multiple by 100 so all the math can handle ints int remainder = (int)(amount * 100); int twentys = remainder / 2000 ; remainder = remainder - (twentys * 2000); int tens = remainder / 1000 ; remainder = remainder - (tens * 1000); int fives = remainder / 500 ; remainder = remainder - (fives * 500); int dollars = remainder / 100 ; remainder = remainder - (dollars * 100); int quarters = remainder / 25 ; remainder = remainder - (quarters * 25); int dimes = remainder / 10 ; remainder = remainder - (dimes * 10); int nickels = remainder / 05 ; remainder = remainder - (nickels * 05); int pennies = remainder / 01 ; System.out.println("Twentys: " + twentys); System.out.println("Tens: " + tens); System.out.println("Fives: " + fives); System.out.println("Dollars: " + dollars); System.out.println("Quarters: " + quarters); System.out.println("Dimes : " + dimes); System.out.println("Nickels : " + nickels); System.out.println("Pennies : " + pennies); } }
Output:
$ java MakeChange Enter total amount: 39.99 Twentys: 1 Tens: 1 Fives: 1 Dollars: 4 Quarters: 3 Dimes : 2 Nickels : 0 Pennies : 4