C 浮点零比较

标签 c floating-point double zero

下面的代码(行与行之间没有任何内容)是否始终为 bool 值 b 生成 true 值?

double d = 0.0;
bool b = (d == 0.0);

我使用的是 g++ 4.8.1 版。

最佳答案

假设 IEEE-754(可能还有大多数浮点表示),这是正确的,因为 0.0 在所有 IEEE-754 中都可以准确表示格式。

现在,如果我们采用不能完全用 IEEE-754 二进制格式表示的另一个文字,例如 0.1:

double d = 0.1;
bool b = (d == 0.1);

这可能会导致 b 对象中的 false 值!

该实现有权为 d 使用例如 double 精度,并为与文字的比较使用更高的精度。

(C99, 5.2.4.2.2p8) "Except for assignment and cast (which remove all extra range and precision), the values of operations with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type."

关于C 浮点零比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20362304/

相关文章:

c++ - AIX 编译器 13.1.3 对 c++ 的双重转换不正确

c - Pragma (OMP) 如何影响执行一段代码所用时间的测量?

c - 如何使用冷缓存启动程序

multithreading - 我可以暂时为线程启用 FTZ 和 DAZ 浮点模式吗?

c++ - 像这样声明浮点常量有什么特别的理由吗? (C 和 C++)

c++ - 异或两个双变量

iphone - double 中的 objective-c stringvalue

c# - 在使用库方面,C/C++/Objective-C 与 C# 相比如何?

c - 递归函数查找回文

PHP/MySQL 忽略小数点右边的数字