2015-11-05 76 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();