C++中std::cout 的输出格式与数值精度使用详解
在 C++ 中,可以使用 <iomanip>
头文件中的 流操纵符(I/O manipulators) 来控制 std::cout
的输出格式与数值精度,尤其适用于浮点数(如 float
、double
、long double
)的精度控制、对齐控制等。
一、常用流操纵符详解
操纵符 | 说明 |
---|---|
std::setprecision(n) | 设置有效数字位数或小数点后位数(取决于格式) |
std::fixed | 以定点格式输出浮点数,setprecision 控制小数点后精度 |
std::scientific | 以科学计数法格式输出浮点数,setprecision 控制小数点后精度 |
std::showpoint | 显示小数点和无意义的尾随零(如 1.000 ) |
std::setw(n) | 设置字段宽度(最小字符数,右对齐) |
std::left / std::right | 设置对齐方式(左对齐 / 右对齐) |
std::setfill(c) | 设置填充字符(与 setw 配合使用) |
二、不同精度控制的使用示例
1. 默认输出(可能是科学计数法或定点格式,取决于平台)
#include <iostream>int main() {double value = 123.456789;std::cout << "Default: " << value << std::endl;return 0;
}
2. 设置有效数字(默认格式)
#include <iostream>
#include <iomanip>int main() {double value = 123.456789;std::cout << "Precision(4): " << std::setprecision(4) << value << std::endl;return 0;
}
3. fixed
+ setprecision
(固定小数位数)
#include <iostream>
#include <iomanip>int main() {double value = 123.456789;std::cout << std::fixed << std::setprecision(3);std::cout << "Fixed(3): " << value << std::endl;return 0;
}
输出:
Fixed(3): 123.457
4. scientific
+ setprecision
#include <iostream>
#include <iomanip>int main() {double value = 123.456789;std::cout << std::scientific << std::setprecision(2);std::cout << "Scientific(2): " << value << std::endl;return 0;
}
输出:
Scientific(2): 1.23e+02
三、更多格式控制示例
5. 对齐与填充
#include <iostream>
#include <iomanip>int main() {double value = 42.0;std::cout << std::setw(10) << std::right << value << std::endl;std::cout << std::setw(10) << std::left << value << std::endl;std::cout << std::setw(10) << std::setfill('*') << value << std::endl;return 0;
}
输出:
42
42
*******42
四、恢复默认状态
使用 std::cout.unsetf(std::ios_base::fixed)
可以取消固定格式(如 fixed/scientific):
std::cout.unsetf(std::ios_base::fixed);
std::cout.unsetf(std::ios_base::scientific);
或者保存输出流的状态再恢复:
std::ios oldState(nullptr);
oldState.copyfmt(std::cout);// 使用各种格式设置
std::cout << std::fixed << std::setprecision(2) << 3.14159 << std::endl;// 恢复格式
std::cout.copyfmt(oldState);
五、常见场景示例小结
场景 | 示例代码 |
---|---|
输出保留 3 位小数 | std::cout << std::fixed << std::setprecision(3); |
显示科学计数法 + 2 位小数 | std::cout << std::scientific << std::setprecision(2); |
设置输出宽度为 10 | std::cout << std::setw(10) << value; |
左对齐 + 填充 | std::cout << std::setw(10) << std::left << std::setfill('-') << value; |