c - 浮点比较中的问题

标签 c floating-point floating-point-conversion

<分区>

void main()
{
    float f = 0.98;
    if(f <= 0.98)
        printf("hi");
    else
        printf("hello");
    getch();
}

我在这里遇到了这个问题。在使用不同的 f 浮点值时,我得到了不同的结果。 为什么会这样?

最佳答案

f正在使用 float精度,但 0.98 在 double 中默认精度,所以语句 f <= 0.98使用 double 进行比较精度。

f因此转换为 double在比较中,但可能会使结果略大于0.98。

使用

if(f <= 0.98f)

或使用 double对于 f相反。


详细...假设floatIEEE single-precisiondoubleIEEE double-precision .

这些类型的 float 以 base-2 表示形式存储。在 base-2 中,这个数字需要无限的精度来表示,因为它是一个重复的小数:

0.98 = 0.1111101011100001010001111010111000010100011110101110000101000...

A float只能存储24位有效数字,即

       0.111110101110000101000111_101...
                                 ^ round off here
   =   0.111110101110000101001000

   =   16441672 / 2^24

   =   0.98000001907...

A double可以存储53位有效数字,所以

       0.11111010111000010100011110101110000101000111101011100_00101000...
                                                              ^ round off here
   =   0.11111010111000010100011110101110000101000111101011100

   =   8827055269646172 / 2^53

   =   0.97999999999999998224...

因此 float 中的 0.98 会变得稍大和更小的 double .

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

相关文章:

floating-point - 哪些单精度 float 需要 9 位有效小数位才能明确表示十进制数?

c# - 如何正确地将 float 从 C# 传递到 C++ (dll)

c++ - 执行两次时产生不同结果的相同浮点计算是否表明不符合 IEEE 754?

c - 浮点运算和机器 epsilon

c - 数组中的输出崩溃

c - 整数宽度与位域声明相关吗?

c++ - 从 cout 中抑制 "minus zero"

在 C 中从 double(GNU 科学库)转换为 SC16Q11

c++ - (C/C++) Windows 7 中的 EOF

c - 尽管在 c 中给出了引用,但对函数的 undefined reference