Java替换变量

时间:2012-07-24 07:58:04

标签: java string variables double

如果直接输入变量(即(5.00,20.00),它会完美地计算变化,但是如果我用购买和金额替换这些值,它不会计算变化吗?

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

1 个答案:

答案 0 :(得分:3)

您正在使用算术和使用double进行比较,只要任何中间值是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变量更改为BigDecimal s,我认为您的问题将会消失。