我已经尝试了多种方法,例如math.Round,并使它们加倍和整数,但我不知道为什么以及在哪舍入到2美分。当我购买32.27并用36支付时,答案是3美元2季度2角钱2美分。
这是我的代码:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Purchase: ");
double purchase = input.nextDouble();
System.out.print("Payment: ");
double amountGiven = input.nextDouble();
int remainingAmount = (int) ((amountGiven - purchase) * 100);
int numOfDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
int numOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
int numOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
int numOfPennies = remainingAmount;
System.out.println("Given $ " + amountGiven + " for a purchase of $ " +
purchase + " we need " + numOfDollars + " dollars " + numOfQuarters +
" quarters " + numOfDimes + " dimes " +
numOfPennies + " cents ");
}
}
最佳答案
如果运行此代码,您将看到问题出在哪里:
final double purchase = 32.27;
System.out.println("Purchase: " + new BigDecimal(purchase));
final double diff = 36 - purchase;
System.out.println("Difference: " + new BigDecimal(diff));
System.out.println("Cent difference: " + (int)(100*diff));
输出将是
Purchase: 32.27000000000000312638803734444081783294677734375
Difference: 3.72999999999999687361196265555918216705322265625
Cent difference: 372
因此,您可以立即发现问题的根源:十进制值
32.27
由最接近的double
值表示,该值稍大一些。差异则稍小一些,在截断后下降了整分。课程:不要将输入解析为
double
,而是解析为into a BigDecimal。关于java - 为什么在我的java change/cashier程序中它总是四舍五入到2美分?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21630855/