2016-05-27 89 views
0

我想問一下更多的解釋。在這裏我的示例程序是java中的double 0.0是大於還是小於0

double diff = 7.500 - 7.500; 
System.out.println(diff); // result 0.0 
if (diff > 0) { 
    System.out.println("+" + diff); //result +0.0 
} else { 
    System.out.println("-" + diff); //result -0.0 
} 

我的結果是-0.0。我的期望是0 == 0.0然後跳過,如果其他條件。但它進入了其他條件。雙倍0.0是大於還是小於0?

+5

如果'diff'不大於零,'else'子句將被執行。這包括'diff'等於零的情況。 – msandiford

+0

@OP:我不認爲你明白'別的'是如何工作的:(但是,你仍然有upvotes。去圖... – sstan

+0

@sstan其實我不想等同案件,但似乎還包括等於零條件 –

回答

1

這就是我的回答:

double diff = 7.500 - 7.500; 
    System.out.println(diff); 

    if(diff>0){ 
     System.out.println("+"+diff); 
    }else if(diff<0){ 
     System.out.println("-"+diff); 
    }else if(diff==0){ 
     System.out.println("="+diff); 
    } 
} 

,我的結果是這樣的:
0.0
= 0.0

必須忘記,0.0等於0是 '否則0.0> 0' 以外的 '0.0> = 0'

3

在你的情況下,你使用(更大)>比較0.0到0,所以0.0不嚴格大於0,(它是相等的)。然後你的程序進入else部分。

if(diff == 0) { 
    System.out.println("+" + diff); //result 0.0 
} else if (diff > 0) { 
    System.out.println("+" + diff); //result +diff 
} else { // diff is less than 0 
    System.out.println("-" + diff); //result -diff 
} 
7

注意如果DIFF> 0您正在檢查 - 所以如果是零,您打印-0.0

相關問題