简介:在C++中,可以使用流操作符和格式化函数来设置输出显示的精度、宽度等。下面是一些常用的方法:
在C++中,可以使用流操作符和格式化函数来设置输出显示的精度、宽度等。下面是一些常用的方法:
<<和setprecision()函数来设置输出显示的精度。例如:在这个例子中,我们使用了
#include <iostream>#include <iomanip>int main() {double num = 3.14159265358979323846;std::cout << std::fixed << std::setprecision(3) << num << std::endl;return 0;}
std::fixed来固定小数点后的位数,然后使用std::setprecision(3)来设置精度为3位。输出结果将是3.142。<<和setw()函数来设置输出显示的宽度。例如:在这个例子中,我们使用了
#include <iostream>#include <iomanip>int main() {int num = 12345;std::cout << std::setw(5) << num << std::endl;return 0;}
std::setw(5)来设置宽度为5个字符。输出结果将是12345,前面会用空格填充到5个字符的宽度。<<和setfill()函数来设置填充字符。例如:在这个例子中,我们使用了
#include <iostream>#include <iomanip>int main() {int num = 12345;std::cout << std::setfill('0') << std::setw(5) << num << std::endl;return 0;}
std::setfill('0')来设置填充字符为’0’。输出结果将是0012345,前面会用’0’填充到5个字符的宽度。