在用作模板参数的类的成员函数中,我有一个包含以下代码的函数:
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;
这个函数的输出是
Element after centering and normalization = 1
and after adding 1 and truncating = 2
then static cast = 1
很明显,最后一行应该给出答案2。
如果我实例化完全相同的类而不将它用作模板参数,我不会得到这个打印输出,而是得到正确的打印输出。
谁能告诉我为什么会这样?
最佳答案
最有可能 x
(a double) 不完全是 1
, 它是 0.9999999...
.通过打印 x==1.0
检查它的确切值或 x<1.0
看看什么是真的。或者在输出中添加更多数字:
cout << "and after adding 1 and truncating = " << setprecision( 15 ) << x+1 << endl;
四舍五入到整数将丢弃逗号后的所有数字,因此 1.999999...
变成 1
.
关于c++ - 用作模板参数的类的成员函数中的奇怪静态转换行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19665358/