这取决于你想要的格式。对于一个固定的小数位, 是这样的:
class FFmt
{
int myWidth;
int myPrecision;
public:
FFmt(int width, int precision)
: myWidth(width)
, myPrecision(precision)
{
}
friend std::ostream& operator<<(
std::ostream& dest,
FFmt const& fmt)
{
dest.setf(std::ios::fixed, std::ios::floatfield);
dest.precision(myPrecision);
dest.width(myWidth);
}
};
应该做的伎俩,所以你可以写:
file << nume << '\t' << FFmt(8, 2) << max ...
(或任何宽度和精度你想要的)。
如果你在做任何浮点工作,你应该在你的工具包中有这样一个操纵器(尽管在很多情况下,它会更适合使用逻辑操纵器,以逻辑命名它所格式数据的含义,例如程度,距离等)。
恕我直言,它也值得扩展操纵器,以便它们保存 格式化状态,并在完整表达式的末尾恢复它。 (我的所有操纵器都是从处理此操作的基类派生出来的。)
[C++ stream output with 3 digits digits after the decimal point。如何?](http://stackoverflow.com/questions/8554441/c-stream-output-with-3-digits-after-the-decimal-point-how) –