如何使两个不同长度的双精度变量相等

How to make two double variables with different length become equal

本文关键字:双精度 变量 何使两      更新时间:2023-10-16

我是Visual C++的新手,我有两个双变量,比如说AA = 10.650406 b = 10.65040606439,我怎样才能使它们相等?

这是一个例子

AA = 10.650406;

if (a == tempfunc(zz)) 执行真函数还 exceute falsefunction

变量 AA 是双精度值,而函数 tempfunc 返回双精度值,如果值 AA 为 10.65040606439,而 tempfunc 的返回值为 10.65040606439。 问题是如何使这些值相等,以便我可以执行函数 TRUEFUNCTION

典型的解决方案是使用"epsilon 值"比较差异。类似的东西

const double eps = 0.000001;  // Adjust this to match the "perecision" you need.
if (abs(a-b) < eps)
{
    // Values are almost equal
}

我想你的问题是:如何对这两个数字进行检查,但不是对所有数字都适用..:

10.123 == 10.1234 (TRUE)
10.123 == 11.123 (FALSE)

如果小数点分隔符后有固定位数(示例中为 6),则可以执行以下操作:

int a2 = a * 10e6;
int b2 = b * 10e6; // (conversion to integers; so the digits smaller than the 6th digit will be removed)

现在您可以检查:

if (a2 == b2)
    {
    //do your thing
    }

总之:

if ( ((int) a*10e6) == ((int) b*10e6))
    {
    //do your thing
    }