1、设置标志字
#include<iostream>
using namespace std;
int main()
{
double x = 22.0 / 7;
int i;
cout << "Output in fixed:\n";
cout.setf(ios::fixed | ios::showpos); //定点输出,显示+
for (i = 1; i <= 5; i++) //用不同精度输出
{
cout.precision(i);
cout << x << endl;
}
cout << "Output in scientific:\n";
cout.setf(ios::scientific, ios::fixed | ios::showpos);
//清除原设置,科学计数法输出
for (i = 1; i <= 5; i++) //用不同精度输出
{
cout.precision(i);
cout << x*1e5 << endl;
}
}
2、使用格式控制符(iomanip中的控制符)
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double x = 22.0 / 7;
int i;
cout << "output in fixed:\n";
cout << setiosflags(ios::fixed | ios::showpos); //定点输出,显示+
for (i = 1; i <= 5; i++)
{
cout << setprecision(i) << x << endl;
}
cout << "output in scientific:\n";
cout << resetiosflags(ios::fixed | ios::showpos) //清除原有设置
<< setiosflags(ios::scientific); //科学计数法输出
for (i = 1; i <= 5; i++)
cout << setprecision(i) << x*1e5 << endl;
}
Iomanip中常见的控制符
Resetiosflags(ios::IFlags) 清除IFlags指定的标志位
Setiosflags(ios::IFlags) 设置IFlags指定的标志位
Setbase(int base) 设置基数,base=8,10,16
Setfill(char c) 设置填充符
Setprecision(int n) 设置浮点数输出精度
Setw(int n) 设置输出宽度
其中 置流表示基数setbase(8)相当于iostream的控制符oct
同理 setbase(10)相当于dec
Setbase(16)相当于hex