在C++的输出中,有时候会遇到要求按照一定的格式输出数据,例如表格中数据的对齐、浮点数小数位数的保留等等。
此时需要用到头文件<iomanip>中的setw(n)函数和setprecision(n)函数。
1、数据对齐
使用setw()函数,注意需要包含<iomanip>头文件。
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
//setw(n)中的n代表接下来的数据占据的宽度,并默认右对齐的方式
//每个需要设置宽度的数据都需要声明一次,如下
cout<<setw(12)<<"test1"<<setw(12)<<"test2"<<endl;
//手动设置为左对齐
cout<<left<<setw(12)<<"test1"<<setw(12)<<"test2"<<endl;
//承接左对齐
cout<<setw(12)<<"test1"<<setw(12)<<"test2"<<endl;
//设回右对齐
cout<<right<<setw(12)<<"test1"<<setw(12)<<"test2"<<endl;
}
输出:
2、数位的保留
首先先分辨数位的保留包括保留x位有效数字和保留x位小数:
保留x位有效数字 是从第一个非零数往后数的位数,使用setprecison(n);
保留x位小数是 保留小数的位数,使用fixed和setprecison(n)。
注意需要包含<iomanip>头文件。
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double x=1234.5678;
//setprecision(n)中的n代表保留的位数
//保留有效数字:
cout<<"保留有效数字:" <<endl;
cout<<setprecision(2)<<x<<endl; //2位时,由有效数字的知识,将使用科学计数法
cout<<setprecision(6)<<x<<endl;
cout<<"\n保留小数位:" <<endl;
//保留n位小数,还需要使用fixed
cout<<fixed<<setprecision(2)<<x<<endl;
cout<<fixed<<setprecision(3)<<x<<endl;
}
输出:
如果要求数据均采用保留两位小数,还可以有以下写法,因为fixed和setprecision()的设置具有黏性设置,对之后输出的值均有效。区分:setw()只对接下来输出的值有效。
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double x1=10.1234;
double x2=11.2345;
double x3=12.3456;
double x4=13.4567;
//统一设置,接下来的数值均保留两位小数
cout<<fixed<<setprecision(2);
cout<<x1<<" "<<x2<<" "<<x3<<" "<<x4<<endl;
}
输出:
3、示例——PTA基础编程题目集:
7-5表格输出
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
cout<<"------------------------------------"<<endl;
cout<<left<<setw(12)<<"Province"<<right<<setw(11)<<"Area(km2)"<<right<<setw(12)<<"Pop.(10K)"<<endl;
cout<<"------------------------------------"<<endl;
cout<<left<<setw(12)<<"Anhui"<<right<<setw(11)<<"139600.00"<<right<<setw(10)<<"6461.00"<<endl;
cout<<left<<setw(12)<<"Beijing"<<right<<setw(11)<<"16410.54"<<right<<setw(10)<<"1180.70"<<endl;
cout<<left<<setw(12)<<"Chongqing"<<right<<setw(11)<<"82400.00"<<right<<setw(10)<<"3144.23"<<endl;
cout<<left<<setw(12)<<"Shanghai"<<right<<setw(11)<<"6340.50"<<right<<setw(10)<<"1360.26"<<endl;
cout<<left<<setw(12)<<"Zhejiang"<<right<<setw(11)<<"101800.00"<<right<<setw(10)<<"4894.00"<<endl;
cout<<"------------------------------------"<<endl;
}
输出:
7-6混合类型数据格式化输入
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double d1,d2;
int i1;
char c1;
while(cin>>d1>>i1>>c1>>d2)
{
cout<<fixed<<setprecision(2);
cout<<c1<<' '<<i1<<' '<<d1<<' '<<d2<<endl;
}
}
输出: