有人可以向我解释为什么float x = 0.1 * 7不会导致x == 0.7为真? [英] Can someone explain to me why float x = 0.1 * 7 does not result in x == 0.7 to be true?

查看:815
本文介绍了有人可以向我解释为什么float x = 0.1 * 7不会导致x == 0.7为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:这里有很多不满的成员,因为这个问题在网站上有一个副本。在我的辩护中,我试图寻找答案,也许我正在使用较差的搜索关键字,但是我找不到一个直接,明确的答案,这个具体的代码示例。没有一个人知道有一个从那里 ** 2009 ** ,然后将链接到这里。



这是一个编码的例子:

  #include< iostream> 
使用namespace std;

int main(){
float x = 0.1 * 7;
if(x == 0.7)
cout<< 真实。\\\
;
else
cout<< FALSE。\\\
;

返回0;
}

这会导致FALSE。但是,当我输出x,它确实输出为0.7。解释?

806-3568 / ncg_goldberg.htmlrel =nofollow>每个计算机科学家应该知道什么是浮点运算。首先, code> 0.1 是 double 类型的字面值。在IEEE 754双精度中,最接近0.1的值是:

  0.1000000000000000055511151231257827021181583404541015625 
如果你乘以7,IEE 754单精度中最接近的可表示值(因为你将它存储在

  0.699999988079071044921875 

正如你所看到的,它几乎是0.7,但并不完全。然后将它转换为 double 作比较,最后比较以下两个值:

  0.699999988079071044921875 == 0.6999999999999999555910790149937383830547332763671875 

当然计算结果为 false


EDIT: There are a lot of disgruntled members here because this question had a duplicate on the site. In my defense, I tried searching for the answer FIRST, and maybe I was using poor searching keywords, but I could not find a direct, clear answer to this specific code example. Little did I know there was one out there from **2009** that would then be linked to from here.

Here's a coded example:

#include <iostream>
using namespace std;

int main() {
    float x = 0.1 * 7;
    if (x == 0.7)
        cout << "TRUE. \n";
    else
        cout << "FALSE. \n";

    return 0;
}

This results in FALSE. However, when I output x, it does indeed output as 0.7. Explanation?

解决方案

Please read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

First of all, 0.1 is a literal of type double. The closest representable value to 0.1 in IEEE 754 double-precision is:

0.1000000000000000055511151231257827021181583404541015625

If you multiply that by 7, the closest representable value in IEE 754 single-precision (since you're storing it in a float) is:

0.699999988079071044921875

Which, as you can see, is almost 0.7, but not quite. This then gets converted to a double for the comparison, and you end up comparing the following two values:

0.699999988079071044921875 == 0.6999999999999999555910790149937383830547332763671875

Which of course evaluates to false.

这篇关于有人可以向我解释为什么float x = 0.1 * 7不会导致x == 0.7为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆