比较 C 中的浮点数 [英] Comparing floating point numbers in C

查看:42
本文介绍了比较 C 中的浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个打印为 0.000000double,我试图将其与 0.0f 进行比较,但未成功.为什么这里有区别?确定双精度值是否为零的最可靠方法是什么?

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 到小数点后六位,例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆