浮点数用C比较 [英] Comparing floating point numbers in C
本文介绍了浮点数用C比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个双击
的打印为 0.000000
和我试图把它比 0.0
,未果。为什么会有这个区别就在这里?什么是最可靠的方法来确定你的双零?
I've got a double
that prints as 0.000000
and I'm trying to compare it to 0.0f
, unsuccessfully. Why is there a difference here? What's the most reliable way to determine if your double is zero?
推荐答案
要确定是否足以零接近,它将为 0.000000
打印6位小数,东西这样的:
To determine whether it's close enough to zero that it will print as 0.000000
to six decimal places, something like:
fabs(d) < 0.0000005
小误差在处理浮点运算可以得到一般比较复杂,虽然。
Dealing with small inaccuracies in floating-point calculations can get quite complicated in general, though.
如果你想有一个更好的想法是什么珍惜你所拥有,尝试用%G
打印,而不是%F
。
If you want a better idea what value you've got, try printing with %g
instead of %f
.
这篇关于浮点数用C比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文