【问题标题】:C : Convert Char To Float Produce 0.000002? [duplicate]C:将字符转换为浮点数产生 0.000002? [复制]
【发布时间】:2017-02-21 22:17:13
【问题描述】:
#include <stdio.h>
#include <conio.h>
int main()
{
int a = 8; float b = 3.9; char c='a';
float hasil = a+b+c;
printf("%f", hasil);
getch();
return 0;
}

我得到结果 108.900002

那么,0.000002 在哪里?

如果我改成

float hasil = a+b;

那么结果将是 11.900000

那么如果我们把char转换成float,那么肯定会加值0.000002? 真的吗 ?如果是,为什么?

谢谢你

【问题讨论】:

  • 浮点值以二进制形式存储。 3.9108.9 的值无法准确表示。实际值很可能是108.90000152587890625

标签: c debugging casting char


【解决方案1】:

char c = 'a' 将值 97 分配给 c97 + 8 + 3.9108.9 的实数,但它没有作为浮点数的精确表示。这就是虚假的0.000002 的来源。正如 Keith Thompson 指出的那样,实际值很可能是 108.90000152587890625,但 %f 格式说明符可能会将其四舍五入。

这是因为浮点数的个数是有限的,而实数是不可数的。

【讨论】:

    【解决方案2】:

    11.9 和 108.9 都不能在 float 中精确表示。如果您使用double,您将获得更好的准确性。

    如果你改变打印的精度,你会看到它们的表现有多准确。

    #include <stdio.h>
    
    int main()
    {
       int a = 8; float b = 3.9; char c='a';
       float hasil = a+b;
       printf("%.16f\n", hasil);
       hasil = a+b+c;
       printf("%.16f\n", hasil);
       return 0;
    }
    

    输出:

    11.8999996185302734
    108.9000015258789062
    

    通过将类型更改为double,我得到了更准确的输出:

    #include <stdio.h>
    
    int main()
    {
       int a = 8; double b = 3.9; char c='a';
       double hasil = a+b;
       printf("%.16f\n", hasil);
       hasil = a+b+c;
       printf("%.16f\n", hasil);
       return 0;
    }
    

    输出:

    11.9000000000000004
    108.9000000000000057
    

    这些结果来自在 Linux 桌面上运行的 gcc。我怀疑你会得到类似的,如果不完全相同的话,也会导致其他常见的编译器。

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 2011-11-25
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-25
      • 2012-06-27
      • 1970-01-01
      相关资源
      最近更新 更多