zoukankan      html  css  js  c++  java
  • C++使用fixed和precision控制小数和有效位数的输出以及setw()设置输出宽度

    头文件iomanip中包含了setiosflags与setprecision,也可以用fixed 代替setiosflags(ios::fixed)

    #include<iostream>//fixed
    #include<iomanip>//包含setiosflags与setprecision
    using namespace std;
    int main()
    {
    	//fixed控制小数,precision控制有效位数
    	double a = 123.6666;
    	printf("%.2f
    ", a); //保留两位小数,输出123.67
     
    	cout << a << endl;   //默认情况下,保留六位有效数字,输出123.667
     
    	cout.setf(ios::fixed); //控制小数
    	cout << a << endl;   //保留六位小数,输出123.666600
     
    	cout.precision(1);    //控制保留位数
    	cout << a << endl;   //保留一位小数,输出123.7
     
    	cout.unsetf(ios::fixed);
     
    	cout << a << endl;   //保留一位有效数字,输出1e+02
     
    	cout << setprecision(2) << a << endl;   //保留两位有效数字,输出1.2e+02
    	cout << setiosflags(ios::fixed) <<setprecision(2) << a << endl;//保留两位小数,输出123.67
    	cout << fixed << setprecision(2) << a << endl;  //同上
    }
    

      

    output:

    123.67
    123.667
    123.666600
    123.7
    1e+002
    1.2e+002
    123.67
    123.67
    

      

    使用setw(n)设置输出宽度时,默认为右对齐,如下:

    std::cout << std::setw(5) << "1" << std::endl;
    std::cout << std::setw(5) << "10" << std::endl;
    std::cout << std::setw(5) << "100" << std::endl;
    std::cout << std::setw(5) << "1000" << std::endl;

    输出结果:

        1
       10
      100
     1000

    若想让它左对齐的话,只需要插入 std::left,如下:

    std::cout << std::left << std::setw(5) << "1" << std::endl;
    std::cout << std::left << std::setw(5) << "10" << std::endl;
    std::cout << std::left << std::setw(5) << "100" << std::endl;
    std::cout << std::left << std::setw(5) << "1000" << std::endl;
    

    输出结果:

    1
    10
    100
    1000
    

    同理,右对齐只要插入 std::right,不过右对齐是默认状态,不必显式声明。 

  • 相关阅读:
    数学基础
    Codeforces Beta Round 84 (Div. 2 Only)
    Codeforces Round 256 (Div. 2)
    Codeforces Round FF(Div. 2)
    Codeforces Round 254 (Div. 2)
    Python3 集合(无序的set)
    Python3 字典(map)
    Python3 元组
    Python3 列表
    初等数论及其应用——唯一分解定理
  • 原文地址:https://www.cnblogs.com/jaszzz/p/12850633.html
Copyright © 2011-2022 走看看