2013-10-16 39 views
1

對於x的值是什麼(x == 0)返回true?是否存在某種類型的保證金,或者當且僅當x = 0的值時,測試是否返回true?在Java中,什麼時候浮點數等於零?

+0

您提問並回答同時 – newuser

+2

@newuser沒有錯,請參閱http://stackoverflow.com/help/self-answer。 –

回答

6

可以編寫一個簡單的方法來找到這個值。

public class FloatEqualsZero { 
    public static void main(String [] args) { 
     float x = 1; 
     while(x != 0 && -x != 0) { 
      x *= 0.1; 
      System.out.println(x); 
     } 
    } 
} 

此輸出以下:

0.1 
0.01 
9.999999E-4 
9.999999E-5 
9.999999E-6 
9.999999E-7 
... 
1.0E-37 
1.0E-38 
1.0E-39 
1.0E-40 
1.0E-41 
1.0E-42 
1.0E-43 
9.8E-45 
1.4E-45 
0.0 

此(和類似的測試)表明,(X == 0),當x是0.0F或等於-0.0f

+1

...或「-0.0f」。 – OldCurmudgeon

1

實際上只爲真當它等於0.0-0.0

public void test() { 
    double x = 0.0; 
    double y = -0.0; 
    double z = 0.0; 
    test(x, y); 
    test(y, z); 
    test(x, z); 
    test(x, (int)y); 
    test(y, (int)z); 
    test(x, (int)z); 

} 

private void test(double x, double y) { 
    System.out.println("x=" + x + " y=" + y + " \"x == y\" is " + (x == y ? "true" : "false")); 
} 

private void test(double x, int y) { 
    System.out.println("x=" + x + " y=" + y + " \"x == y\" is " + (x == y ? "true" : "false")); 
} 

打印

x=0.0 y=-0.0 "x == y" is true 
x=-0.0 y=0.0 "x == y" is true 
x=0.0 y=0.0 "x == y" is true 
x=0.0 y=0 "x == y" is true 
x=-0.0 y=0 "x == y" is true 
x=0.0 y=0 "x == y" is true 
4

Math.signum(x) == 0

所有其他嘗試檢查浮動x == 0是否可能會失敗。

但Math.signum()是如此基本,它永遠不會失敗。