0

If the variables are entered directly (i.e (5.00, 20.00) it calculates the change perfectly, but if I substitute the values with purchase and amount it doesn't calculate the change?

public static void makeChange()
   {

       double purchase;
       double tendered;

       Scanner scan = new Scanner (System.in);

       System.out.println ("How much was the Purchase?");
       purchase = scan.nextDouble(); 
       System.out.println ("Amount Tendered"); 
       tendered = scan.nextDouble();


       System.out.println("Processing Transaction");
       int ch[] = cd.makeChange(purchase, tendered); // does not calculate change correctly





           ...continued
4

1 回答 1

3

您正在使用算术和比较 using double,一旦任何中间值是不能由 a 精确表示的数字,就会产生不可预测的结果double。例如,考虑这个看似无辜的循环:

double value = 1.0;
double dime = 0.1;
while (value > 0) {
   value -= dime;
   System.out.println(value);
}

这打印:

0.9
0.8
0.7000000000000001
0.6000000000000001
0.5000000000000001
0.40000000000000013
0.30000000000000016
0.20000000000000015
0.10000000000000014
1.3877787807814457E-16
-0.09999999999999987

关于为什么会这样的进一步阅读可以在这里找到:What Every Computer Scientist Should Know About Floating-Point Arithmetic

正如您在上一个问题中所建议的,将您的double变量更改为BigDecimals ,我认为您的问题将会消失。

于 2012-07-24T08:15:17.623 回答