用作模板参数的类的成员函数中奇怪的静态强制转换行为
Strange static cast behaviour in a member function of class used as template parameter
在用作模板参数的类的成员函数中,我有一个包含以下代码的函数:
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.0
或x<1.0
来检查其确切值,看看什么是真实的。或者在输出中添加更多数字:
cout << "and after adding 1 and truncating = " << setprecision( 15 ) << x+1 << endl;
四舍五入为整数将丢弃逗号后的所有数字,因此1.999999...
变为1
。
相关文章:
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 在 Stream C++ 文本之前有一个额外的换行符
- 流:CSV 文件中的换行符
- 将缓冲区复制到剪贴板 [换行错误]
- 如何在三元条件运算符中添加换行符和连接? :在 C++ 中
- Clang-格式:在多行语句之后的换行符上打开大括号
- 如何正确转发/换行static_cast?
- 在输出流中插入换行符
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- QProcess::readAllStandardOutput() 和换行符
- 如果有换行符,clang 格式不会附加大括号
- 创建一个简单的前向迭代器,该迭代器在循环缓冲区的"end"处自动换行
- C++在标点符号后将字符串换行
- 提取后返回换行符的C++istream.get()
- 如何在出现换行符之前将多个整数作为输入?
- 正则表达式 获取两个换行符之间的文本
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 在字符串中输入换行符