我的 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);
结果如下:
由于您要转换为 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) ");
这将为您提供您期望的金额:
关于java - 变化计算器减一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499333/