在C++中,setprecision
, fixed
, scientific
, hex
, oct
, 和 dec
是用于格式化输出的控制符,它们都是 <iomanip>
头文件中的一部分。
setprecision
setprecision(int n)
用于设置浮点数的输出精度,即小数点后保留的位数。如果与 fixed
或 scientific
一起使用,它将决定小数点后或指数表示法中小数的位数。
示例:
#include <iostream>
#include <iomanip>
usingnamespace std;
int main() {
double number = 3.14159265;
cout << setprecision(3) << number << endl;
// 输出: 3.142
cout <<fixed << setprecision(3) << number << endl;
// 输出: 3.142 (固定小数点)
cout << scientific <<setprecision(3) << number << endl;
// 输出: 3.142e+00 (科学记数法)
return 0;
}
fixed
fixed
操作符用于设置浮点数以固定小数点的形式输出,即总是显示指定位数的小数,而不管其实际值大小。
示例:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.1415926535;
cout <<fixed << setprecision(2) << pi << endl; // 输出: 3.14
return 0;
}
scientific
scientific
操作符使得浮点数以科学记数法形式输出,即一个1到10之间的数字乘以10的某个幂。
示例:
#include <iostream>
#include <iomanip>
int main() {
double e = 2.718281828459;
std::cout << std::scientific << std::setprecision(3) << e << std::endl;
// 输出: 2.718e+00
return 0;
}
hex, oct, dec
这些操作符用于改变整数的输出基数。
hex
将整数以十六进制形式输出,其中A-F表示10-15。oct
将整数以八进制形式输出。dec
将整数以十进制形式输出,这是默认设置。
示例:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int value = 255;
cout << dec << value <<endl; // 输出: 255 (十进制)
cout << hex << value << endl; // 输出: ff (十六进制)
cout <<oct << value << endl; // 输出: 377 (八进制)
return 0;
}
记得在进行格式设置后,使用 std::resetiosflags
或重新设置新的格式来清除之前的效果,以避免意外的格式继承。