gpt4 book ai didi

C 浮点零比较

转载 作者:太空狗 更新时间:2023-10-29 15:24:18 25 4
gpt4 key购买 nike

下面的代码(行与行之间没有任何内容)是否始终为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com