c++ - 为什么 float 取 0.699999 而不是 0.7

标签 c++ visual-c++ floating-point dev-c++

<分区>

此处 x 取 0.699999 而不是 0.7,但 y 取 0.5 作为分配值。你能告诉我这种行为的确切原因是什么吗?

#include<iostream>
using namespace std;

int main()
{
float x = 0.7;
float y = 0.5;
if (x < 0.7)
{
if (y < 0.5)
   cout<<"2 is right"<<endl;
else 
   cout<<"1 is right"<<endl;
}
else 
   cout<<"0 is right"<<endl; 

cin.get();
return 0;
}

最佳答案

Internet 上有很多关于 IEEE float 的内容。

0.5 = 1/2

所以可以写成两个的幂之和

0.7 = 7/10 = 1/2 + 1/5 = 1/2 + 1/8 + a bit more... etc

bit more 永远不可能恰好是 2 的幂,因此您可以得到最接近的值。

关于c++ - 为什么 float 取 0.699999 而不是 0.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17612654/

相关文章:

c++ - 仅针对二元运算符防止隐式转换运算符

C++__LINE__宏的类型是什么

c++ - 寻求 DDX 的替代品

visual-c++ - 如何获取光标下的像素颜色?

c++ - 在 C++ 中声明方法 extern

c++ - 错误 : expected primary-expression before 'template' - what am I doing wrong?

c++ - std::string 的语言环境相关排序

floating-point - IEEE 754 标准中哪里指定了 `Inf * 0` 的结果?

python - 在 SQLAlchemy 中查询浮点值

c++ - float 的验证和转换