当我将双精度数与零进行比较时,为什么Resharper会抱怨? [英] Why does Resharper complain when I compare a double to zero?

查看:135
本文介绍了当我将双精度数与零进行比较时,为什么Resharper会抱怨?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我愿意

double d = 0;
if (d == 0) {
  ...
}

Resharper在比较d == 0时抱怨比较浮点数与相等运算符.舍入值时可能会损失精度".

Resharper complains at the comparison d == 0 about "Comparison of floating point number with equality operator. Possible loss of precision while rounding values."

为什么?将精确的零表示为double或float会很困难吗?

Why? It cannot be difficult to represent exact zero as a double or a float can it?

我知道,如果将我与其他值(例如0.2)进行比较,而没有确切的二进制表示形式,那么这样的警告将是有意义的.

I understand such a warning would be relevant if I compared to some other value such as 0.2 for which there is no exact binary representation.

推荐答案

Resharper不会分析double变量如何获得其值.

Resharper does not analyze how the double variable got its value.

经过几次计算后,双精度值很少是精确的,因此锐化器会警告您,将双精度值与精确值进行比较不是一个好主意.

After a few calculations a double value is rarely exact so resharper warns you that comparing a double with an exact value is not a good idea.

double x = Math.Sqrt(2);
double d = x * x;

Console.WriteLine(d == 2);

这篇关于当我将双精度数与零进行比较时,为什么Resharper会抱怨?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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