Java币找零评估

标签 java

我目前正在编写一个程序,该程序仅打印归还零钱时使用的硬币。但是,我收到 2 个断言错误,这些错误是在服务器后端进行评估的。没有示例测试值,您必须自己编写。

expected:[...  Change Due $0.01  [1 penny] ]
but was:[...  Change Due $0.01  [2 pennies] ]
expected:[...  Change Due $0.19  [1 dime 1 nickel 4 pennies ]
but was:[...  Change Due $0.19  [2 dimes ]
/**
 * Calculate the amount of change based on user input.
 * Output coins with an output greater than 0. 
 * @param args returns an argument array for string objects
 */
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Total amount? ");
    double total = input.nextDouble();
    System.out.print("Cash payment? ");
    double payment = input.nextDouble();
    double changeDue = payment - total;

    System.out.println();
    System.out.printf("Change Due $%.2f\n\n", changeDue);

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

    int[] coins = {dollars,quarters,dimes,nickels,pennies};
    String[] names = {"dollar", "quarter", "dime", "nickel", "penny"};

    for (int i = 0; i < 5; i++) {
        if (coins[i] == 1) {
            System.out.println(coins[i] + " " + names[i]);
        } else if (coins[i] > 1 && i != 4) {
            System.out.println(coins[i] + " " + names[i] + "s");
        }
    }

    if (coins[4] > 1) {
        System.out.println(coins[4] + " pennies");
    }
}

最佳答案

你的代码实际上工作得很好。但问题是,如果您只打印“changeDue”变量,然后查看,您可以看到末尾有一个 9。它打印为 0.010000000000000009,而不是您期望的 0.010000000000000000。然后乘以 100 后上限为 2。然后你得到 2 便士作为答案。

实际上这似乎是小数存储方式的问题。 ( Java Double value = 0.01 changes to 0.009999999999999787 ) 这里解释得很好。所以你可能需要稍微改变一下你的方法。

关于Java币找零评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58254074/

相关文章:

java - Gradle 项目 --Failed to configure a DataSource'url' attribute is not specified and no embedded datasource could be configured

java - GWT 项目编译不工作 - 没有错误,在 SUPERDEV 模式下完美运行

java - 从字符串数组中删除空元素,其中 "All elements are null"

java - 如何获取具有文本和复选框字段的整个表的值 jsp 到 servlet

java - Apache CXF : How to secure JAX-RS web service with basic authentication

java - 出现异常时到底会发生什么

java - 如何验证Spring MVC Web应用程序中是否已设置连接池?

java - 无法弄清楚我的数组列表的输出

java - 如何在 Spring Boot 中验证 Rest 请求

java - 在 Mountain Lion 中安装 jpype