C++ 用作模板参数的类的成员函数中奇怪的静态强制转换行为

C++ 用作模板参数的类的成员函数中奇怪的静态强制转换行为,c++,templates,casting,member-functions,C++,Templates,Casting,Member Functions,在用作模板参数的类的成员函数中,我有一个包含以下代码的函数: double x = /*Something operation returning double*/; x /= CubeWidth; /*CubeWidth is a class member*/ cout << "Element after centering and normalization = " << x << endl; cout << "and after adding

在用作模板参数的类的成员函数中,我有一个包含以下代码的函数:

double x = /*Something operation returning double*/;
x /= CubeWidth; /*CubeWidth is a class member*/
cout << "Element after centering and normalization = " << x << endl;
cout << "and after adding 1 and truncating = " << x+1 << endl;
cout << "then static cast = " << (int) x+1 << endl;
显然,最后一行应该给出一个答案2

如果我实例化了完全相同的类而没有将其用作模板参数,那么我不会得到这个打印输出,而是得到了正确的输出


有人能告诉我为什么会这样吗?

最有可能的是
x
(双精度)不完全是
1
,而是
0.999999…
。通过打印
x==1.0
x检查其精确值好的问题是为什么。不过,我知道如何解决这个问题——将表达式放在括号中。例如
((int)x+1)
。我也会等待好的解释。编辑:如果这个解决方案不起作用,那么我必须是丹尼尔·弗雷写的。@j_random_hacker不,
+
的优先级高于
@j_random_hacker:
1你说你是的时候并没有截断,但你和演员们在一起。@DanielFrey:哎哟,你说得对
我想你是对的,但这种影响已经开始随机出现。我只是再次运行了测试,没有做任何更改,只是我不再连接到wifi!这可能有关系吗?我知道我在抓救命稻草…@Plamen宇宙射线,“相对Mondfeuchtigkeit”…-但最后更可能的是你没有展示的
x
的计算。无论如何,只要让你的代码更安全,添加更多的数字或允许一个小的增量,例如
(int)(x+1.000001)
。也许会有帮助。
Element after centering and normalization = 1
and after adding 1 and truncating = 2
then static cast = 1
cout << "and after adding 1 and truncating = " << setprecision( 15 ) << x+1 << endl;