我必须为我的班级做一个分配,允许用户键入两个金额-第一个应该是总销售金额,第二个应该是交给收银员的找零金额。该程序需要计算所需的找零,并告诉收银员使用最少数量的钞票和硬币将多少钱返还给客户。使用$ 20、10、5、1和0.25、0.10、0.05和0.01。我还需要包含一个while loop
以确保收银员得到的金额大于应付金额。
到目前为止,我有以下内容,但不知道从这里出发:
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Enter sale amount less than $100
System.out.println("Enter the sale amount: ");
double price = input.nextDouble();
//Enter amount of money handed to cashier less than $100
System.out.println("Enter the amount of money handed to the cashier: ");
double payment = input.nextDouble();
double difference = payment - price;
int num20 = (int)(difference / 20);
System.out.println("num20 = " + num20);
difference = difference % 20;
System.out.println("difference = " + difference);
int num10 = (int)(difference / 10);
System.out.println("num20 = " + num10);
difference = difference % 10;
System.out.println("difference = " + difference);
int numQtr = (int)(difference / .25);
System.out.println("numqtr = " + numQtr);
int numDime = (int)(difference / .10);
System.out.println("numDime = " + numDime);
}
最佳答案
使用mod运算符和除法在每个步骤中查找值
29 % 20 -> 9
(int) (29 / 20) -> 1
9 % 10 -> 9
(int) (9 / 10) -> 0
请注意,将除法结果转换为整数会把返回的值截断为整数。
关于java - Java-找零的纸币和硬币数量最少,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46596510/