2015-11-05 73 views
1

我的代碼中:我如何平等比較兩個雙打?

else if (returnShortestTime() == shortTime[1]) 

returnShortestTime返回最小的雙,並比較了雙存儲的方法,是因爲這不只是與雙A ==雙B I如何可以比較兩個雙打我的代碼,看看他們是否是平等的?

+1

你提的問題是很難理解 - 你可以顯示與預期與實際輸出一個完整的例子嗎? – assylias

+0

實際的輸出不工作...所有我的if語句比較兩個雙打,並且不能有'else'語句,所以只有條件if/else if語句和至少一個必須運行但它不在 –

+0

我聽說過比較兩個雙打直接返回假 –

回答

2

一般而言,您實際上可以使用==作爲Java中的基本數據類型。將浮點數與相等進行比較通常不是個好主意的原因是由於floating point precision error。有兩種解決方案可以比較兩個浮點數(雙打)的相等性,您可以使用Java的BigDecimal或檢查兩個數之間的差是否小於某個閾值(通常稱爲Epsilon value) 。

使用BigDecimal

BigDecimal foo = new BigDecimal(returnShortestTimeAsString() /*String Representation of your returnShortestTime() method*/); 
BigDecimal bar = new BigDecimal(shortTimeAsString[1] /*String Representation of this array value*/); 
if(foo.compareTo(bar) == 0 /*If they are equal*/) doStuff(); 

使用的埃普西隆

if(Math.abs(returnShortestTime() - shortTime[1]) < Math.ulp(1.0) /*This is the Epsilon value*/) doStuff();