Double vs Float - Java

时间:2016-04-03 17:49:32

标签: java double

我有以下计划。这是由我的老师给予的乐趣。我对结果感到惊讶。

代码:

public class Testing {

    public static void main(String[] args) {

         float     piF =  3.141592653589793f;   // value assigned has float precision
         double    piD =  3.141592653589793;   //  value assigned has double precision
         final double THRESHOLD = .0001; 
         if( piF == piD) 
            System.out.println( "piF and piD are equal" ); 
         else 
            System.out.println( "piF and piD are not equal" ); 
         if( Math.abs( piF - (float) piD ) < THRESHOLD ) 
            System.out.println( "piF and piD are considered equal" ); 
         else 
            System.out.println( "piF and piD are not equal" ); 

    }

}

结果:

piF and piD are not equal
piF and piD are considered equal

为什么piF和piD不相等?实际上Math.abs()做什么使两者相同?

1 个答案:

答案 0 :(得分:0)

我在终端中运行了这个,然后为piF和piD的值添加了print语句,结果如下:

piF and piD are not equal
piF and piD are considered equal
piF = 3.1415927
piD = 3.141592653589793

当你在两者之间进行直接比较时,它们是不相等的。但是当你将piD转换为float类型时,就会变成这样:

(float) piD = 3.1415927

如果您不了解结果,请尝试在变量上使用print语句,这是了解这些内容的好方法!

以下是我添加的打印陈述供您参考:

    System.out.println("piF = " + piF);
    System.out.println("piD = " + piD);

    System.out.println("(float) piD = " + (float) piD);