如果先前将它初始化为零,将double与零比较是正确的吗? [英] Is it correct to compare a double to zero if you previously initialized it to zero?

查看:229
本文介绍了如果先前将它初始化为零,将double与零比较是正确的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用 == 比较一个double不是一个明智的做法。然而我想知道如果检查是否双重初始化可能是危险的或不。例如,如果知道一个变量doubleVar不能为零,如果它已被初始化,是否可以这样做?

I learnt that comparing a double using == is not a wise practice. However I was wondering if checking if a double has been initialized could be dangerous or not. For example, knowing that a variable doubleVar cannot be zero if it has been initialized, is it safe to do this?

Foo::Foo(){
    doubleVar = 0.0;  // of type double
}

void Foo::Bar(){
    if(doubleVar == 0){ // has been initialized?
        //...
    }else{
        //...
    }
}


推荐答案

在IEEE-754中,长篇小说:

In IEEE-754, long story short:

double d;

d = 0.0;
d == 0.0   // guaranteed to evaluate to true, 0.0 can be represented exactly in double

double d;

d = 0.1;
d == 0.1   // not guaranteed to evaluate to true

这篇关于如果先前将它初始化为零,将double与零比较是正确的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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