iomanip 库

cout 输出控制 百度百科用法实例

实例1

#include 
#include 

using namespace std;

int main() {

    double a = 123.456789012345;

    cout << a << endl << endl; // 123.457 默认的precision=6

    // setprecision 表示有效数字位数
    cout << setprecision(9) << a << endl; // 123.456789
    cout << setprecision(6) << a << endl << endl; // 123.457 恢复默认格式

    // setiosflags 中设置flag之后,在后面会一直用,除非更改了flag,或者reset
    // ios::fixed 设置浮点数以固定的小数位数显示

    cout << setiosflags(ios::fixed) << a << endl << endl; // 123.456789,前面确定了precision=6

    // ios::scientific 设置浮点数以指数形式显示
    cout << resetiosflags(ios::fixed); // 清除前面的输出格式
    cout << setiosflags(ios::scientific) << setprecision(2) << a << endl; // 科学计数法,2位小数

    return 0;
}
123.457

123.456789
123.457

123.456789

1.23e+02

实例2

#include 
#include 

using namespace std;


int main() {
    cout << 1e-6 << endl; // 默认情况
    cout << setiosflags(ios::fixed) << 1e-6 << endl; // 设置定点小数
    cout << resetiosflags(ios::fixed); // 必须cout才能清除前面的格式
    cout << 1e-6 << endl; // 又恢复成默认情况
    return 0;
}
1e-06
0.000001
1e-06

你可能感兴趣的:(iomanip 库)