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\n", 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,不过右对齐是默认状态,不必显式声明。 

posted @ 2020-05-08 15:11  ジャスミン  阅读(1387)  评论(0编辑  收藏  举报