Java类将零钱分解成硬币?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25796079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:09:19  来源:igfitidea点击:

Java class to break down change into coins?

java

提问by cooldudsk

I am working on a java assignment where you enter the price of an object and the amount a theoretical customer handed you for the item. Then the program returns how much you owe them, and breaks it down into dollars, quarters, dimes, nickles, and pennies that you should give them.

我正在做一个 java 任务,你输入一个对象的价格和一个理论客户交给你的项目金额。然后程序返回您欠他们的金额,并将其分解为您应该给他们的美元、四分之一、一角硬币、镍币和便士。

Basically here's what it would look like when it runs

基本上这是它运行时的样子

What was the purchase price? (exclude the decimal in calculation if it helps you)
$98.50
How much money did you pay with? (exclude the decimal)
$100.00
The purchase price was $98.50
You payed $100.0
You received $1.50 in change.
0 one hundred dollar bill(s)
0 fifty dollar bill(s)
0 twenty dollar bill(s)
0 ten dollar bill(s)
0 five dollar bill(s)
1 one dollar bill(s)
2 quarter(s)
0 dime(s)
0 nickel(s)
0 penny/pennies

购买价格是多少?(如果对您有帮助,请排除计算中的小数)
$98.50
您支付了多少钱?(不包括小数)
100.00 美元
购买价格为 98.50 美元
您支付了 100.0 美元
您收到了 1.50 美元的找零。
0 一百美元的钞票
0 五十美元的钞票
0 二十美元的钞票
0 十美元的钞票
0 五美元的钞票
1 一美元的钞票
2 季
币 0 角钱(s)
0 镍
0 便士/便士

I understand most of it, but I cant seem to wrap my mind around the breakdown of the change handed back. Here's my code so far, but if someone could show me how to break down the change.

我理解其中的大部分内容,但我似乎无法理解交回的零钱的故障。到目前为止,这是我的代码,但如果有人可以告诉我如何分解更改。

import java.util.*;
public class ChangeTendered {

    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);

        System.out.println("Enter the purchase price: ");
        double price = scan.nextDouble();
        System.out.println("Enter the amount payed: ");
        double ammountPayed = scan.nextDouble();

        double changeDue = ammountPayed - price;

        int dollars = (int)changeDue;

        System.out.println("Return"+ dollars+ "Dollars");

        scan.close();
    }

}

On a side note, I just cast the changeDue to an int in order to chop off the decimal and get the dollars due, if that caused any confusion.

附带说明一下,我只是将 changeDue 转换为 int 以去掉小数点并获得到期的美元,如果这会引起任何混淆。

采纳答案by StackFlowed

Here is an initial approach

这是一个初步的方法

    int change = (int)(Math.ceil(changeDue*100));
    int dollars = Math.round((int)change/100);
    change=change%100;
    int quarters = Math.round((int)change/25);
    change=change%25;
    int dimes = Math.round((int)change/10);
    change=change%10;
    int nickels = Math.round((int)change/5);
    change=change%5;
    int pennies = Math.round((int)change/1);

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

You can add more code to the do it for currency notes as well.

您也可以添加更多代码来为纸币做这件事。

回答by user3808597

What I did was convert it to a string then do a decimal split to separate the change and dollars.

我所做的是将其转换为字符串,然后进行十进制拆分以将零钱和美元分开。

import java.util.Scanner;
import java.text.DecimalFormat;
public class register 
{
  public static void main(String[] args)
  {
    DecimalFormat decimalFormat = new DecimalFormat("0.00");

    Scanner kb = new Scanner(System.in);
    System.out.print("How much does this item cose? -> ");
    double cost = kb.nextDouble();
    System.out.print("How many will be purcased? -> ");
    double quanity = kb.nextDouble();
    double subtotal = (cost * quanity);
    double tax = (subtotal * .06);
    double total = (subtotal + tax);
    System.out.print("How much money has been tendered? -> ");
    double tendered = kb.nextDouble();
            double change = (tendered - total);

        int dollars = (int)change;
        int twenties = dollars / 20;
        int dollars1 = dollars % 20;
        int tens = dollars1 / 10;
        int dollars2 = dollars % 10;
        int fives = dollars2 / 5;
        int dollars3 = dollars % 5;
        int ones = dollars3;

        String moneyString = decimalFormat.format(change);
        String changeString = Double.toString(change); 
        String[] parts = moneyString.split("\.");
        String part2 = parts[1]; 
        double cents5 = Double.parseDouble(part2);

        int cents = (int)cents5;
        int quarters = cents / 25;
        int cents1 = cents % 25;
        int dimes = cents1 / 10;
        int cents2 = cents % 10;
        int nickels = cents2 / 5;
        int cents3 = cents % 5;
        int pennies = cents3;

        System.out.println("Cost: " + "$" + decimalFormat.format(cost));
        System.out.println("Quanity: " + quanity);
        System.out.println("Subtotal: " + "$" + decimalFormat.format(subtotal));
        System.out.println("Tax: " + "$" + decimalFormat.format(tax));
        System.out.println("Total: " + "$" + decimalFormat.format(total));
        System.out.println("Tendered: " + "$" + decimalFormat.format(tendered));
        System.out.println("Change: " + "$" + moneyString);


        System.out.println(twenties + " Twenties");
        System.out.println(tens + " Tens");
        System.out.println(fives + " Fives");
        System.out.println(ones + " Ones");
        System.out.println(quarters + " Quarters");
        System.out.println(dimes + " Dimes");
        System.out.println(nickels + " Nickels");
        System.out.println(pennies + " Pennies");

  }
}

回答by Shawn_Fan

From what I can understand, you need to break the returned money into different bills: 100, 50, 20, 10, 5 ... etc.

根据我的理解,你需要把退回的钱分成不同的钞票:100、50、20、10、5……等等。

I think you can use 'division' to solve the problem in Java. The following pseudo code is how you might solve the problem:

我认为您可以使用“除法”来解决 Java 中的问题。以下伪代码是您解决问题的方法:

//For example:
double changeDue = 15.5;
double moneyLeft = changeDue;

int oneHundred = moneyLeft  / 100;
moneyLeft -= oneHundred * 100;

int fifty = moneyLeft  / 50;
moneyLeft -= fifty*50 ;

...

//Just remember to 'floor' the result when divided by a double value:

int quarter = Math.floor( moneyLeft / 0.25);
moneyLeft -= quarter * 0.25 ;
...//Until your minimum requirement.

//Then print out your results.

Hope it helps.

希望能帮助到你。

回答by TheCodingFrog

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class ChangeTenderedWorking {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the purchase price: ");
        BigDecimal price = scan.nextBigDecimal();
        System.out.println("Enter the amount paid: ");
        BigDecimal amountPayed = scan.nextBigDecimal();
        Map<Denomination, Integer> changeDue = getDenomination(amountPayed, price);

        for(Denomination denomination : changeDue.keySet()) {
            System.out.println("Return " + denomination + " bill(s) : "+ changeDue.get(denomination));
        }
        scan.close();
    }

    public static Map<Denomination, Integer> getDenomination(BigDecimal amountPayed, BigDecimal price) {
        BigDecimal change = amountPayed.subtract(price);
        System.out.println("Return change -- "+ change);
        Map<Denomination, Integer> changeReturn = new LinkedHashMap<Denomination, Integer>();
        for(Denomination denomination : Denomination.values()) {

            BigDecimal[] values = change.divideAndRemainder(denomination.value, MathContext.DECIMAL32);
            if(!values[0].equals(BigDecimal.valueOf(0.0)) && !values[1].equals(BigDecimal.valueOf(0.0))) {
                changeReturn.put(denomination, values[0].intValue());
                change = values [1];
            }

        }
        return changeReturn;
    }

    enum Denomination {
        HUNDRED(BigDecimal.valueOf(100)),
        FIFTY(BigDecimal.valueOf(50)),
        TWENTY(BigDecimal.valueOf(20)),
        TEN(BigDecimal.valueOf(10)),
        FIVE(BigDecimal.valueOf(5)),
        TWO(BigDecimal.valueOf(2)),
        ONE(BigDecimal.valueOf(1)),
        QUARTER(BigDecimal.valueOf(0.25)),
        DIME(BigDecimal.valueOf(0.10)),
        NICKEL(BigDecimal.valueOf(0.5)),
        PENNY(BigDecimal.valueOf(0.1));

        private BigDecimal value;

        Denomination(BigDecimal value) {
            this.value = value;
        }
    }
}