Java:也添加要计算的更改

时间:2019-03-17 21:02:26

标签: java

我正在寻找是否有人可以帮助我找出如何添加到我的代码中,以在给定我输入的数量的情况下显示四分之一,一角硬币,五分之一硬币和几美分硬币的数目。

这对我的作业来说是额外的功劳,我很想知道如何做,但还没有从类似的问题(如我要问的问题)中找到所需的内容。因此,如果有人可以帮助我,我将不胜感激。 (美元账单转换效果很好)

public static void main(String[] args) {

    double userInput = 0.0;
    int bills;

    Scanner inputScanner = new Scanner(System.in);

    System.out.println("Please enter the amount of money you would like: ");
    userInput = inputScanner.nextDouble();

    if (userInput < 0.0) {
        System.out.println("Goodbye!");
        inputScanner.close();
    }

    if (userInput > 0.0) {

        bills=(int)(userInput/20);
        System.out.println("You will receive:\n" + bills + " twenty dollar bills,");
        userInput=(userInput-(bills*20));
        bills=(int)(userInput/10);
        System.out.println(bills+" ten dollar bills,");
        userInput=(int)(userInput-(bills*10));
        bills=(int)(userInput/5);
        System.out.println(bills+" five dollar bills,");
        userInput=(userInput-(bills*5));
        bills=(int)(userInput/1);
        System.out.println(bills+" one dollar bills.");

    }

}

1 个答案:

答案 0 :(得分:1)

使用双精度的小数部分可能会很棘手,因为JVM会进行近似处理。例如,以下代码

double userInput = 123.39D;
double change = userInput - (int)userInput;  // suppose to be 0.39
System.out.println(change);

产生输出0.39000000000000057

一种解决方法是将100乘以一个int。这样可以有效地将“前”两位十进制数字“移动”到点的左侧,在这里很容易进行数学运算以获得所需的提名:

public static final int QUARTER = 25;
public static final int DIME = 10;
public static final int NICKEL = 5;

    double userInput = 123.39D;
    double changeDouble = userInput - (int)userInput;  // get smaller-than-1-dollar change
    int changeInt = (int)(changeDouble * 100);  // move two digits from right to left of decimal dot
    System.out.println("quarters: " + changeInt / QUARTER);
    changeInt -= (changeInt / QUARTER) * QUARTER;
    System.out.println("dimes: " + changeInt / DIME);
    changeInt -= (changeInt / DIME) * DIME;
    System.out.println("nickels: " + changeInt / NICKEL);
    changeInt -= (changeInt / NICKEL) * NICKEL;
    System.out.println("pennies: " + changeInt);