当比较相等是否可以使用`==`? [英] When comparing for equality is it okay to use `==`?

查看:121
本文介绍了当比较相等是否可以使用`==`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当比较相等时,可以使用 ==

When comparing for equality is it okay to use ==?

例如:

int a = 3;
int b = 4;

如果检查是否相等,应使用:

If checking for equality should you use:

if (a == b)
{
     . . .
}

如果使用浮点数,情况会改变吗?

Would the situation change if floating point numbers were used?

推荐答案

' == '非常适合整数值。

您应比较浮点数的相等性;使用容忍方法:

You should not compare floats for equality; use an tolerance approach:

if (fabs(a - b) < tolerance)
{
   // a and b are equal to within tolerance
}

这篇关于当比较相等是否可以使用`==`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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