c++ - 匹配 printf 格式与 iomanip

标签 c++ floating-point printf cout modifiers

我有一些旧的 C 代码,我试图复制 C++ 中的行为。它使用 printf 修饰符:“%06.02f”。

我天真地认为 iomanip 也有同样的能力,并且做到了:

cout << setfill('0') << setw(6) << setprecision(2)

当我尝试输出测试编号 123.456 时,printf 产生:

123.46

但是 cout 产生:

1.2+e02

我可以在 iomanip 中做些什么来复制这个,还是我必须回去使用 printf

[ Live Example ]

最佳答案

尝试 std::fixed :

std::cout << std::fixed;

Sets the floatfield format flag for the str stream to fixed.

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

关于c++ - 匹配 printf 格式与 iomanip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275542/

相关文章:

math - float 学有问题吗?

python - 极值的 logit 和反 logit 函数

math - float 学有问题吗?

c - 使用 getchar 输入字符串

C++转换题

c++ - 未构造对象的调用方法 : Legal?

c++ - C/C++ 打印自定义 EOL

c - 什么编译器不支持 printf 标志中的 "%#x"样式?

c++ - 如何在 BackgroundSubtractorMOG2 中禁用阴影跟踪?

c++ - 指向包含指向 vector 指针的结构的 vector