答案是使用 fixed 和 setprecision(2) 配合 iomanip 头文件实现保留两位小数输出,格式设置后持续生效,需手动取消或重置恢复默认。

在C++中,使用 cout 输出保留两位小数,可以通过头文件 <iomanip> 提供的格式化工具实现。最常用的方法是结合 std::fixed 和 std::setprecision 来控制浮点数的输出精度。
1. 引入头文件 <iomanip>
要使用格式化输出功能,必须包含 <iomanip> 头文件:
// 示例代码 #include <iostream> #include <iomanip> // 必须引入 using namespace std;2. 使用 fixed 和 setprecision 设置小数位数
std::fixed 表示以定点十进制格式输出浮点数,std::setprecision(n) 设置小数点后保留 n 位数字。
double num = 3.14159; cout << fixed << setprecision(2) << num << endl; // 输出:3.14如果不使用 fixed,setprecision(2) 会设置总共显示的有效数字位数(例如 3.1),而不是小数点后两位。
立即学习“C++免费学习笔记(深入)”;
3. 常见用法示例
double a = 2.5, b = 1.73214; cout << "a = " << fixed << setprecision(2) << a << endl; cout << "b = " << b << endl; // 输出: // a = 2.50 // b = 1.73注意:setprecision 和 fixed 是持续生效的,一旦设置,后续所有通过 cout 输出的浮点数都会遵循该格式,直到重新设置或取消。
4. 恢复默认输出格式
如果只想对某一个数值做格式化,可以在输出完成后恢复默认格式:
cout << fixed << setprecision(2) << num << endl; cout.unsetf(ios_base::fixed); // 取消 fixed 格式 cout << setprecision(6); // 恢复默认精度基本上就这些。只要记住固定搭配:fixed + setprecision(2),就能轻松实现保留两位小数的输出。不复杂但容易忽略细节。










