由于直接的浮点比较是有风险的,因此我正在编写一个包装器类来检查浮点数的关系操作。
#include<iostream>
#include <cmath>
template<unsigned int round_off_digits=10>
class FloatRelationalOperators
{
private:
inline static double calcEpsilonValue()
{
int localVar=round_off_digits;
double withLocalVar=pow(10, (localVar * -1 ));
double WithoutLocalVar=pow(10, (round_off_digits * -1 ));
std::cout<<"withLocalVar: "<<withLocalVar<<" "<<"WithoutLocalVar :"<<WithoutLocalVar;
return WithoutLocalVar;
}
public:
inline static bool notequal(double a,double b)
{
double res=fabs(a-b);
if( res <= calcEpsilonValue())
{
return true;
}
else
{
return false;
}
return false;
}
};
int main()
{
FloatRelationalOperators<>::notequal(10.1,10.0);
}
我正在尝试从最大舍入位数计算epsilon值。
当我运行程序时,得到的结果如下:
withLocalVar: 1e-10 WithoutLocalVar :inf
当在函数中直接使用非类型模板参数时,为什么我的答案是错误的?
我做错什么了吗?
round_off_digits
是一个无符号值,然后将其乘以-1
一个很大的无符号整数。如果您将其更改为int
有效
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句