【发布时间】:2023-12-13 12:05:01
【问题描述】:
我的 Java 计算器不会输出正确的变化量。它减去一分钱,我不知道为什么。
我最初将更改声明为单独的变量,但我只是将用户输入乘以 100,但我仍然遇到同样的问题。
//this is where the variables are declared
double penny = 0.01;
double nickel = 0.05;
double dime = 0.10;
double quarter = 0.25;
double half_dollar = 0.50;
double dollar_coin = 1.00;
double user_input = 0;
int total_penny, total_nickel, total_dime, total_quarter,
total_half_dollar, total_dollar_coin;
Scanner in = new Scanner (System.in);
//this is where the user can input data
System.out.println("What amount would you like change for: ");
user_input = in.nextDouble();
//this is where the users data will be processed
total_dollar_coin = (int) (user_input / 1.0);
user_input = user_input % 1.00;
total_half_dollar = (int) (user_input / 0.50);
user_input = user_input % 0.50;
total_quarter = (int) (user_input / 0.25);
user_input = user_input % 0.25;
total_dime = (int) (user_input / 0.10);
user_input = user_input % 0.10;
total_nickel = (int) (user_input / 0.05);
user_input = user_input % 0.01;
total_penny = (int) (user_input / 0.01);
//this is where the information will be outputted to the user
System.out.println("Your change will be: " + total_dollar_coin + " dollar
coin(s) ");
System.out.println(total_half_dollar + " half dollar coin(s) " +
total_quarter
+ " quarter(s) ");
System.out.print(total_dime + " dime(s) " + total_nickel + " nickel(s) " +
total_penny + " penny (or pennies) ");
}
}
【问题讨论】:
-
(A) 将您的代码和数据简化为输入-输出-期望的一个最小示例。 (B) 切勿将
double/Double或float/Float用于金钱或其他任何地方if you want accuracy。 -
不要用浮点数来赚钱。正如您所发现的那样,它并不精确。使用
BigDecimal。
标签: java calculator netbeans-8