c++ - float 比较给出不同的结果

标签 c++ c floating-point

看下面两段代码,告诉我答案差异很大的原因。

#include<stdio.h>
int main() {
    float a = 0.9;
    if(a<0.9)
        printf("hi"); // This will be the answer
    else
        printf("bye");
    return 0;
}

如果我们将 0.9 更改为 0.8,则会打印 else 的语句:

#include<stdio.h>
int main() {
    float a = 0.8;
    if(a<0.8)
        printf("hi");
    else
        printf("bye");//this will be the answer
    return 0;
}

那么为什么当我们只改变一个数字时输出会改变?

最佳答案

这个错误是由于浮点精度,因为你正在比较 float输入 double值(value)。尝试将它与浮点文字进行比较:if(a<0.8f)

我建议你阅读根据 wikipedia article , 它详细解释了为什么会发生错误。

关于c++ - float 比较给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7580352/

相关文章:

c - 为什么 memcmp() 相差 1 时返回 256?

c - 堆是否像内存中的堆栈一样具有固定大小,如果两者发生冲突会发生什么

language-agnostic - 使用 float 作为哈希表的键是否安全?

c++ - fatal error C1083 : Cannot open include file: 'xyz.h' : No such file or directory?

c - 为什么这段代码在第二次迭代时在 "*(str_arr + i) = (char*)calloc((strlen(temp_str) + 1), sizeof(char));"行触发断点

c++ - cmath 精度误差中的底函数

c - 在嵌入式 C 中将 float 与 sprintf() 一起使用

c++ - C++ 程序员应该使用哪些 C++ 习语?

c++ - 与迭代乘法相比,std::pow() 的数值稳定性如何?

c++ - 为什么我的 OpenGL 不绘制任何东西?