C : Strange error when using float and double

标签 c floating-point

Possible Duplicate:
strange output in comparision of float with float literal
Comparison of float and double variables

我在 C 中对 double 和 float 进行了测试,但我无法解释原因。

    float x = 3.4F;
    if(x==3.4)
        printf("true\n");
    else printf("false\n");
    double y = 3.4;
    if (y==3.4)
        printf("true\n");
    else printf("false\n");

结果将是 False 和 True。请帮我解释一下。

最佳答案

3.4 不能精确地表示为 double ,其原因与三分之一不能使用有限位数精确地表示为以 10 为基数的十进制数相同 - 表示会重复出现。

因此, double 字面量 3.4 实际上是最接近 3.4 的 double 值。 3.4F 是最接近 3.4 的浮点值,但与最接近的 double 值不同。

当您将浮点型与 double 型进行比较时,浮点型将转换为 double 型,这不会改变其值。

因此,3.4F != 3.4,就像0.3333 != 0.33333333

关于C : Strange error when using float and double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11202752/

相关文章:

c++ - 将 cos 和 sin 存储到 vector 中并获得奇怪的值

c - IEEE 754 : is v *= -1 always guaranteed to be the same as v = -v?

c++ - vscode-cpptools 错误 : "cl.exe build and debug is only usable when VS Code is run from the Developer Command Prompt for VS."

c - 在 C 中与 mmap 共享 vector

c - g_file_new_for_path() 导致段错误

使用牛顿拉夫森求立方根

linux-kernel - linux内核模块中的浮点运算(再次)

c - 如何使用 C 设置 unix 命令,尤其是 "system()"?

c - 复合语句( block )是否被 ANSI C 中的括号表达式包围?

floating-point - 究竟定点比浮点更准确的地方在哪里