我的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) ");
}
}
答案 0 :(得分:0)
如果您调试这一点,你会看到,例如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) ");
这会给你你所期望的量: