代码改变世界

cout的输出格式初探3

2015-07-09 09:43  GarfieldEr007  阅读(233)  评论(0编辑  收藏  举报
 1 #include <iostream>
 2 #include <iomanip>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     double f=2.0/3.0,f1=0.000000001,f2=-9.9;
 8     cout<<f<<' '<<f1<<' '<<f2<<endl; //正常输出
 9     cout.setf(ios::showpos); //强制在正数前加+号 //表示出正负号
10     cout<<f<<' '<<f1<<' '<<f2<<endl;
11     cout.unsetf(ios::showpos); //取消正数前加+号
12     cout.setf(ios::showpoint); //强制显示小数点后的无效0
13     cout<<f<<' '<<f1<<' '<<f2<<endl;
14     cout.unsetf(ios::showpoint); //取消显示小数点后的无效0
15     cout.setf(ios::scientific); //科学记数法
16     cout<<f<<' '<<f1<<' '<<f2<<endl;
17     cout.unsetf(ios::scientific); //取消科学记数法
18     cout.setf(ios::fixed); //按点输出显示
19     cout<<f<<' '<<f1<<' '<<f2<<endl;
20     cout.unsetf(ios::fixed); //取消按点输出显示
21     cout.precision(18); //精度为18,正常为6
22     cout<<f<<' '<<f1<<' '<<f2<<endl;
23     cout.precision(6); //精度恢复为6
24     cout<<f<<' '<<f1<<' '<<f2<<endl;
25     
26     cout<<"----------------------------"<<endl;
27     
28     //使用操作算法,效果相同
29     cout<<f<<' '<<f1<<' '<<f2<<endl; //正常输出
30     cout<<setiosflags(ios::showpos); //强制在正数前加+号
31     cout<<f<<' '<<f1<<' '<<f2<<endl;
32     cout<<resetiosflags(ios::showpos); //取消正数前加+号
33     cout<<setiosflags(ios::showpoint); //强制显示小数点后的无效0
34     cout<<f<<' '<<f1<<' '<<f2<<endl;
35     cout<<resetiosflags(ios::showpoint); //取消显示小数点后的无效0
36     cout<<setiosflags(ios::scientific); //科学记数法
37     cout<<f<<' '<<f1<<' '<<f2<<endl;
38     cout<<resetiosflags(ios::scientific); //取消科学记数法
39     cout<<setiosflags(ios::fixed); //按点输出显示
40     cout<<f<<' '<<f1<<' '<<f2<<endl;
41     cout<<resetiosflags(ios::fixed); //取消按点输出显示
42     cout<<setprecision(18); //精度为18,正常为6
43     cout<<f<<' '<<f1<<' '<<f2<<endl;
44     cout<<setprecision(6); //精度恢复为6
45     cout<<f<<' '<<f1<<' '<<f2<<endl; 
46 
47     return 0;
48 }

程序运行结果如下: