检查预置双精度值的有效性 [英] Validity of checking exact value of preset double
问题描述
我有时在我的代码中执行以下操作,当我懒惰:
double d = 0;
$我可以总是指望如果我设置一个
...
if(condition1)d = 1.0;
...
if(d == 0){//不确定这是否有效
}
double
为0的事实,p $ p>
我可以稍后用
$ bd == 0
可靠地检查代码吗?
我理解,如果我在上面的代码中对
d
进行计算,我不能期望d
正好0
但如果我设置它,我会认为我可以。解决方案是的,对于大多数情况(即不包括NaN ):在赋值
a = b;
之后,条件a == b
为true。因此,只要你只分配和比较你分配的东西,这应该是可靠的,即使对于浮点类型。I sometimes do the following in my code when I am being lazy:
double d = 0; ... if( condition1 ) d = 1.0; ... if (d == 0) { //not sure if this is valid }
can I always count on the fact that if I set a
double
to be0
I can later check in the code for it withd == 0
reliably?I understand that if I do computations on
d
in the above code, I can never expectd
to be exactly0
but if I set it, I would think I can. All my testing so far on various systems seem to indicate that this is legitimate.解决方案Yes, for most cases (i.e. excluding NaN): After the assignment
a = b;
the conditiona == b
is true. So as long as you're only assigning and comparing to the thing you assign from, this should be reliable, even for floating-point types.这篇关于检查预置双精度值的有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!