使用==比较Java中的浮点数有什么问题? [英] What's wrong with using == to compare floats in Java?
本文介绍了使用==比较Java中的浮点数有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据此java.sun页面 ==
是Java中浮点数的等式比较运算符。
According to this java.sun page ==
is the equality comparison operator for floating point numbers in Java.
但是,当我输入此代码时:
However, when I type this code:
if(sectionID == currentSectionID)
进入我的编辑器并运行静态分析,我得到:JAVA0078浮点值与==相比
into my editor and run static analysis, I get: "JAVA0078 Floating point values compared with =="
有什么问题使用 ==
来比较浮点值?这样做的正确方法是什么?
What is wrong with using ==
to compare floating point values? What is the correct way to do it?
推荐答案
测试浮点数的正确性的正确方法是:
the correct way to test floats for 'equality' is:
if(Math.abs(sectionID - currentSectionID) < epsilon)
其中epsilon是一个非常小的数字,如0.00000001,具体取决于所需的精度。
where epsilon is a very small number like 0.00000001, depending on the desired precision.
这篇关于使用==比较Java中的浮点数有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文