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

Strange static cast behaviour in a member function of class used as template parameter

本文关键字:静态 换行 转换 函数 参数 成员      更新时间:2023-10-16

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

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(双精度)不完全是1,它是0.9999999...。通过打印x==1.0x<1.0来检查其确切值,看看什么是真实的。或者在输出中添加更多数字:

cout << "and after adding 1 and truncating = " << setprecision( 15 ) << x+1 << endl;

四舍五入为整数将丢弃逗号后的所有数字,因此1.999999...变为1