将double与0进行比较是错误的:doubleVariable == 0? [英] Is it wrong to compare a double to 0 like this: doubleVariable==0?

查看:1138
本文介绍了将double与0进行比较是错误的:doubleVariable == 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以这样做吗?

double doubleVariable=0.0;
if (doubleVariable==0) {
   ...
}



Or this code would suffer from potential rounding problems?

推荐答案

或者这个代码会受到潜在的四舍五入问题的困扰,如果你只是要比较0作为右侧的比较将自动转为双倍。另一方面,如果你在哪里比较== 0.10000001

Nope it's perfectly legal if you are only going to compare against 0 as the right side of comparison will automatically casted to double. On the other hand, it would yield all the round-off errors if you where to compare against == 0.10000001

你会更好,或者将关于float的讨论阅读到0比较这里:是吗安全检查浮点值是否相等于0?

You are better or reading the discussion about float to 0 comparison here: Is it safe to check floating point values for equality to 0?

此外,本次讨论对于浮点数上的奇怪精度问题非常有帮助:为什么这个问题的结果不同?

Also this discussion is very informative about weird precision problems on floats: Why the result is different for this problem?

ie以下将产生错误:

i.e. below will yield false:

double d1 = 1.000001; double d2 =0.000001;
Console.WriteLine((d1-d2)==1.0);

这篇关于将double与0进行比较是错误的:doubleVariable == 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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