简体   繁体   English

Java-找零的纸币和硬币数量最少

[英]Java - Least number of bills and coins for change

I have to do an assignment for my class that allows the user to key in two amounts - the first should be the total sale amount and the next would be the amount of change handed to the cashier. 我必须为我的班级做一个分配,允许用户键入两个金额-第一个应该是总销售额,第二个应该是交给收银员的找零额。 The program needs to calculate the change needed and tell the cashier how many of each monetary amount to return to the customer using the least number of bills and coins. 该程序需要计算所需的找零,并告诉收银员使用最少数量的钞票和硬币将多少钱返还给客户。 Using $20, 10, 5, 1 and 0.25, 0.10, 0.05, and 0.01. 使用$ 20、10、5、1和0.25、0.10、0.05和0.01。 I also need to include a while loop to make sure the cashier is given an amount greater than the amount due. 我还需要包括一个while loop ,以确保收银员的付款额大于应付额。

I have the following so far, but don't know where to go from here: 到目前为止,我有以下内容,但不知道从这里出发:

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);     

}

Use the mod operator and division to find values at each step 使用mod运算符和除法在每个步骤中查找值

29 % 20 -> 9
(int) (29 / 20) -> 1

9 % 10 -> 9
(int) (9 / 10) -> 0

please note that casting the result of a division to an integer will truncate the returned value to a whole number. 请注意,将除法结果转换为整数会把返回的值截断为整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM