zoukankan      html  css  js  c++  java
  • C++格式化控制台输出

    格式化控制台输出

    下面的函数都是流操作,也就是在"<<"或">>"(流操作符)间使用,定义在<iomanip>头文件中

    #include  <iomanip>
    操作 描述
    setprecision(n) 设置一个浮点数的精度
    fixed 显示小数位,常与setprecision(n)联合使用
    showpiont 即使没有小数位也要用0补齐,常与setprecision(n)联合使用
    setw(width) 指定打印字段的宽度
    left 调整输出到左边
    right 调整输出到右边

    1. setprecision(n)

    double number = 123.4567;
    cout << setprecision(3) << number << endl;
    //123
    cout << setprecision(4) << number << endl;
    //123.5
    cout << setprecision(5) << number << endl;
    //123.46
    cout << setprecision(6) << number << endl;
    //123.457

    2.fixed

    double number = 123232456743.4567;
    cout << number << endl;
    //1.23232e+011
    //这是科学计数法的形式,即1.23232*10^11
    //要想以非科学计数法的形式显示就要使用fixed函数
    cout << fixed << number << endl;
    //123232456743.456696
    //由于浮点数的精度问题导致小数位有一些偏差
    cout << fixed << setprecision(4) << number << endl;
    //123232456743.4567

    3. showpoint

    cout << setprecision(6);
    cout << 12.3 << endl;
    //12.3
    cout << showpoint << 12.3 << endl;
    //12.3000
    cout << showpoint << 12.30 << endl;
    //12.3000

    4. setw(width)

    cout << setw(8) << "C++" << setw(6) << 101 <<endl;
    cout << setw(8) << "Java" << setw(6) << 101 <<endl;
    cout << setw(8) << "HTML" << setw(6) << 101 <<endl;

    程序运行结果:

      

     注意:stew函数只能影响下一个也就是说如果没有setw(6),101就会紧贴着前面。

    这时候又会有一个问题,就是当我们设置的宽度小于输出项的宽度会怎么样?

    答:当我们设置的宽度小于输出项的宽度时,宽度会自动增加为输出项的宽度,相当于没有设置宽度。

    5. left和right

    setw操作默认的设置是右对齐,我们可以使用left使其左对齐

    cout << left;
    cout << setw(8) << "C++" << setw(6) << 101 <<endl;
    cout << setw(8) << "Java" << setw(6) << 101 <<endl;
    cout << setw(8) << "HTML" << setw(6) << 101 <<endl;

  • 相关阅读:
    Cocos2D学习笔记(1)- 常用的类
    C++头文件的重复定义错误处理
    python3中的sort和sorted函数
    numpy提供的快速的元素级数组函数
    HDU 1180 诡异的楼梯(BFS)
    POJ 1020 Anniversary Cake(DFS)
    POJ 1564 Sum It Up(DFS)
    POJ 1190 生日蛋糕(DFS)
    HDU 1026 Ignatius and the Princess I(BFS+优先队列)
    HDU 1172 猜数字(DFS)
  • 原文地址:https://www.cnblogs.com/bwjblogs/p/12606294.html
Copyright © 2011-2022 走看看