4

我对数据类型有一个奇怪的问题:double。

这是我的代码:

public class Example {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        double a = 1.0;
        for(int i =0; i<10;i++){
            System.out.println("Number => " + a );
            a += 0.1;
        }
    }

}

输出应该是:

Number => 1.0
Number => 1.1
Number => 1.2
Number => 1.3
Number => 1.4
Number => 1.5
Number => 1.6
Number => 1.7
Number => 1.8
Number => 1.9

但是,此代码示例的结果是:

Number => 1.0
Number => 1.1
Number => 1.2000000000000002
Number => 1.3000000000000003
Number => 1.4000000000000004
Number => 1.5000000000000004
Number => 1.6000000000000005
Number => 1.7000000000000006
Number => 1.8000000000000007
Number => 1.9000000000000008

我使用 eclipse 来编译这个代码块。我在netbeans上试过,但没有任何改变。

应该如何发生?有任何想法吗?

问候

4

2 回答 2

1

这并不容易。我会使用 Commons-Math

for (int i = 0; i < 10; i++) {
    a = Precision.round(a, 1);   // <- round to 1 digit after decimal point
    ...

我认为唯一的 Java SE 替代方案是

a = Double.parseDouble(String.format(Locale.US, "%.1f", a));
于 2013-05-30T14:14:29.160 回答
0

根据javadoc

If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).

这里是源

于 2013-05-30T14:26:00.730 回答