输出格式化:setprecision(), stew(), stefill(), setbase(), fixed() 的用法

一、setprecision()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream.h>

#include <iomanip.h> //要用到格式控制符

int main()

{

double amount = 22.0/7;

cout << amount <<endl;

cout << setprecision(0) << amount <<endl; //C++最小的有效位数为1,所以作为有效位数设置为1来看待  

<< setprecision(1) << amount << endl;

<< setprecision(2) << amount << endl;

<< setprecision(3) << amount << endl;

<< setprecision(4) << amount << endl;

cout << setiosflags(ios::fixed) << setprecision(8) << amount << endl;

cout << setiosflags(ios::scientific) << amount << endl;

cout << setprecision(6) <<amount << endl; //重新设置成原默认设置

return 0;

}

运行结果为:

3.14286

3

3

3.1

3.14

3.143

3.14285714

3.14285714e+00

3.14286

注:
1.在用浮点表示的输出中,setprecision(n)表示有效位数(小数点两边一共多少个数字,n代表数字)。

2.C++默认的流输出数值有效位是6。

setiosflags(ios::fixed)是用定点方式表示实数

如果setprecision(n)与setiosflags(ios::fixed)合用,可以控制小数点右边的数字个数。

setiosflags(ios::scientific)是用指数方式表示实数。

如果如果setprecision(n)与setiosflags(ios::scientific)合用,可以控制指数表示法(科学计数法)的小数位。

二、
setw()用法: 通俗地讲就是预设宽度

如:cout << setw(5) << 666 << endl;

结果是:

(空格)(空格)666

setfill() 用法 : 就是在预设宽度中如果已存在没用完的宽度大小,则用设置
的字符填充

如: cout << setfill('q') << setw(5) << 666 << endl;

结果是:

qq666

▲setbase(int n) : 将数字转换为 n 进制.

如:

1
2
3
4
5
 cout<<setbase(8)<<setw(5)<<255<<endl;

cout<<setbase(10)<<setw(5)<<255<<endl;

cout<<setbase(16)<<255<<endl;

结果是:

1
2
3
4
5
(空格)(空格)377

(空格)(空格)255

(空格)(空格)ff

三、fixed()
fixed()就是用一般的方式输出浮点数,而不是科学计数法。