参考:c语言中float为什么不能直接用==与0比较
2018-01-05 10:08
323 查看
因为如果a与b差不多时,得出的是大于呢?还是小于?
所以只能用abs(a-b)<=0.0000001,来判断a是否等于b,
Floating point math is not exact. Simple values like 0.2 cannot be precisely represented using binary floating point numbers, and the limited precision of floating point numbers means that slight changes in the order of operations can change the result.
Different compilers and CPU architectures store temporary results at different precisions, so results will differ depending on the details of your environment. If you do a calculation and then compare the results against some expected value it is highly unlikely
that you will get exactly the result you intended.
In other words, if you do a calculation and then do this comparison:
if (result == expectedResult)
then it is unlikely that the comparison will be true. If the comparison is true then it is probably unstable – tiny changes in the input values, compiler, or CPU may change the result and make the comparison be false.
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
所以只能用abs(a-b)<=0.0000001,来判断a是否等于b,
参考:c语言中float为什么不能直接用==与0比较
Floating point math is not exact. Simple values like 0.2 cannot be precisely represented using binary floating point numbers, and the limited precision of floating point numbers means that slight changes in the order of operations can change the result.Different compilers and CPU architectures store temporary results at different precisions, so results will differ depending on the details of your environment. If you do a calculation and then compare the results against some expected value it is highly unlikely
that you will get exactly the result you intended.
In other words, if you do a calculation and then do this comparison:
if (result == expectedResult)
then it is unlikely that the comparison will be true. If the comparison is true then it is probably unstable – tiny changes in the input values, compiler, or CPU may change the result and make the comparison be false.
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
相关文章推荐
- c语言中float为什么不能直接用==与0比较
- float为什么不能直接用==作比较
- 关于为什么整型不能和float,double型直接比较大小的原因
- 为什么浮点数不能直接与零值比较?谢谢
- 探讨float类型的数值,为什么两个float不能直接相等
- 探讨float类型的数值,为什么两个float不能直接相等
- 为什么两个float类型的数值不能直接相等
- size_type和int为什么不能直接比较
- 为什么Float类型不能直接相等
- 探讨float类型的数值,为什么两个float不能直接相等
- 两个 Long 类型为什么不能直接用==比较
- 两个 Long 类型为什么不能直接用==比较
- 为什么不能直接调用dealloc而是release
- InetAddress为什么不能new而可以直接拿来用
- C语言 为什么数组名(数组首地址)不能进行加减操作?
- 为什么不能直接通过IP访问网站
- 为什么不能直接通过IP访问网站
- c语言的label后面不能直接跟变量申明
- sqlserver 数据库里面金额类型为什么不建议用float,实例告诉你为什么不能。
- 你不知道的c语言之为什么数组的大小不能是变量