java - 变化计算器减一

标签 java calculator netbeans-8

我的 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) ");
    }

}

最佳答案

如果你调试这个,你会看到例如51.43 你的最后一行:

total_penny = (int) (user_input / 0.01);

结果如下:

enter image description here

由于您要转换为 int,这将导致“意外输出”,在本例中为 零 (0) - 请参阅上面有关准确性的第二条评论中提供的链接。 尽管如此,解决该问题的一个可能的解决方案(作为教育练习)是执行以下操作:

BigDecimal total_penny;
int total_nickel, total_dime, total_quarter, total_half_dollar, total_dollar_coin;

然后在您的 total_penny 行中:

user_input = user_input % 0.05;    --> you have 0.01 typo here
total_penny = BigDecimal.valueOf(user_input / 0.01);

格式化total_penny输出并输出:

String penny = NumberFormat.getInstance().format(total_penny);
System.out.println("..." + penny + " penny (or pennies) ");

这将为您提供您期望的金额:

enter image description here

关于java - 变化计算器减一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499333/

相关文章:

java - 将 WildFly 应用程序服务器与 NetBeans IDE 结合使用

java - Ubuntu Java : Find a specific program's pid and kill the program

java - 使用 Java 的 Selenium Webdriver 中的小数位为 2 个值

java - Azure REST API 使用 java 获取存储 Blob 大小详细信息

C# 数学计算器

javascript - jQuery年龄计算不是计算闰年

netbeans - 有没有办法调整 Netbeans 以在编程区域旁边逐行显示历史记录?

java - Java线程池抛出RejectedExecutionException的单元测试

java - 如何获得 Cos 和 Tan 函数的用户友好值?

jakarta-ee - Netbeans:如何创建Gradle Java EE项目?