在程序中使用非类型模板参数而未给局部变量赋值时,会导致意外结果

Unexpected result when non type template parameter is used in the program without assigning to local variable?

本文关键字:赋值 局部变量 结果 意外 程序 类型 参数      更新时间:2023-10-16

由于直接的浮点比较是有风险的,所以我编写了一个包装器类来检查浮点数的关系操作。

#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,它可以工作

http://cpp.sh/8yflj