1. 问题现象
- 问题源码
#include <iostream>
using namespace std;
int main()
{
// ... 其他代码略
cout << endl
<< std::setprecision(2)
<< 1 / 3.0 << endl;
}
- 错误信息
[build] P1223_test.cpp:49:18: error: ‘setprecision’ is not a member of ‘std’
[build] 49 | << std::setprecision(2)
[build] | ^~~~~~~~~~~~
2. 解决办法
#include <iomanip> // 注意包含这个头文件
#include <iostream>
using namespace std;
int main()
{
// ... 其他代码略
cout << endl
<< std::setprecision(2)
<< 1 / 3.0 << endl;
}
3. 原因说明
虽然是用来控制输出的浮点数的精度的, 但是在单独的头文件
<iomanip>
中声明, 不在iostream
中;
/usr/include/c++/9/iomanip
中的一段源码
185 struct _Setprecision { int _M_n; };
186
187 /**
188 * @brief Manipulator for @c precision.
189 * @param __n The new precision.
190 *
191 * Sent to a stream object, this manipulator calls @c precision(__n) for
192 * that object.
193 */
194 inline _Setprecision
195 setprecision(int __n)
196 { return { __n }; }