繁体   English   中英

比较浮点值会在Java中产生意外结果

[英]Comparing float values giving unexpected results in java

我在下面的程序中执行浮点值比较。 这是非常基本的。.在比较过程中,十进制长度有一些技巧。 请帮助我理解这一点。

class C
{
    public static void main(String args[])
    {
        Float pi = new Float(3.13999999f);
        if (pi > 3.13999999) {
             System.out.print("pi is bigger than 3. ");
        }
        else if (pi < 3.13999999){
            System.out.print("pi is less than 3. ");
        }
    }
}

结果:pi大于3

然后我从所有三个值中删除了最后一位数字(9)

class C
{
    public static void main(String args[])
    {
        Float pi = new Float(3.1399999f);

        if (pi > 3.1399999) {
          System.out.print("pi is bigger than 3. ");
        }
        else if (pi < 3.1399999){
          System.out.print("pi is less than 3. ");
        }
    }
}

现在的结果是:pi小于3

当然结果是出乎意料的。 您绝对不能/不能做精确的浮点数比较。

通常,如果要比较两个浮点值(A和B),则要进行差值AB,然后将其与可接受的误差进行比较(假设为0.00001)。

另一种方法是使用Float.compareTo(Float)方法。

    Float pi = new Float(3.139999f);
    int result = pi.compareTo(new Float(3.139999f));

    if (result == 0) {
        System.out.println("they are equal");
    } else {
        System.out.println("something went wrong");
    }

输出:

they are equal

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM