面试题答案
一键面试在C++中,通过<iostream>
库进行基本的输入输出操作,利用<iomanip>
库实现格式化输出。以下是相关操作及代码示例:
-
设置浮点数精度: 使用
setprecision(n)
函数,n
为想要设置的精度。 -
设置宽度: 使用
setw(n)
函数,n
为想要设置的宽度。 -
设置对齐方式:
left
:左对齐right
:右对齐internal
:符号左对齐,数值右对齐
#include <iostream>
#include <iomanip>
#include <string>
int main() {
double num = 123.456789;
std::string str = "Hello, World!";
// 设置浮点数精度为4
std::cout << std::setprecision(4) << num << std::endl;
// 设置宽度为10,右对齐
std::cout << std::setw(10) << num << std::endl;
// 设置宽度为15,左对齐
std::cout << std::left << std::setw(15) << str << std::endl;
// 设置宽度为15,右对齐
std::cout << std::right << std::setw(15) << str << std::endl;
// 设置宽度为15,符号左对齐,数值右对齐(对于浮点数)
double negativeNum = -123.456;
std::cout << std::internal << std::setw(15) << negativeNum << std::endl;
return 0;
}
上述代码展示了如何使用<iomanip>
库中的函数来对浮点数和字符串进行格式化输出,设置精度、宽度和对齐方式。