在程序中使用非类型模板参数而未给局部变量赋值时,会导致意外结果
Unexpected result when non type template parameter is used in the program without assigning to local variable?
由于直接的浮点比较是有风险的,所以我编写了一个包装器类来检查浮点数的关系操作。
#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
,它可以工作
相关文章:
- 为"adjacent"变量赋值时出现问题
- 非常量变量只读位置的赋值
- 变量在使用赋值语句赋值后恢复为以前的值
- 局部变量保留函数中的值
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 如何在函数外部访问函数中局部变量的值?
- 初始值设定项列表与构造函数赋值与变量定义
- 如何将值从指针永久赋值到变量
- 获取一个数组变量,该数组变量的大小是用要进行赋值的变量定义的
- 这个静态变量赋值给局部函数中的指针有什么问题
- 当赋值给变量时,数字改变值
- C++ 在循环"if"内丢失赋值的变量
- 使用赋值给函数返回值的局部变量或直接使用函数
- 将pair的成员赋值给变量
- 为什么我不能用if和if else语句赋值给变量
- 在程序中使用非类型模板参数而未给局部变量赋值时,会导致意外结果
- 将cin的输出赋值给变量
- C++ 如何判断值是否被赋值到变量中
- 操作未赋值给变量的结果
- Lambda赋值局部变量