检查预置双精度值的有效性 [英] Validity of checking exact value of preset double

查看:149
本文介绍了检查预置双精度值的有效性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时在我的代码中执行以下操作,当我懒惰:

  double d = 0; 
...
if(condition1)d = 1.0;

...
if(d == 0){//不确定这是否有效
}
double 为 0的事实,p $ p>
$ b
我可以稍后用 d == 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 be 0 I can later check in the code for it with d == 0 reliably?

I understand that if I do computations on d in the above code, I can never expect d to be exactly 0 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 condition a == 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屋!

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