格式化输出做题遇到的问题
必要头文件
#include<iomanip>
1. 保留几位小数
两种简单地使用方式 其实就是一种
第一种:cout<<setiosflags(ios::fixed)<<setprecision( n)<<num;这里的n就是要保留几位小数
第二种:cout<<fixed<<setprecision(n)<<num;其实就是第一种的简写
看代码:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double num = 3.1415926535;
cout << "原数:" << num << endl; //3.1415926535
cout << "保留两位小数:" << endl;
//{
cout << setiosflags(ios::fixed) << setprecision(2) << num << endl;//3.14
cout << fixed << setprecision(2) << num << endl; //3.14
//}
cout << setiosflags(ios::fixed) << setprecision(6) << num << endl;//3.141590
cout << fixed << setprecision(7) << num << endl; //3.1415900
//显然当保留位数大于实际位数是它会补零
system("pause");
return 0;
}
结果:
原数:3.14159
保留两位小数:
3.14
3.14
3.141590
3.1415900
那么问题来了,是不是每次输出都要写一次这种格式
当然------------------------------------------------------不是
LOOK 下边
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double num = 3.1415926535;
cout << "原数:" << num << endl; //3.1415926535
cout << "保留两位小数:" << endl;
//{
cout << setiosflags(ios::fixed) << setprecision(2) << num << endl;//3.14
cout << num << endl; //3.14
//}
system("pause");
return 0;
}
结果:
原数:3.14159
保留两位小数:
3.14
3.14
2. 保留几位有效数字
cout<<setprecision(n)<<num;这里相比上边保留小数位少了一部分 记住就好 n代表要保留的位数
看代码:
#include<iomanip>
using namespace std;
int main()
{
double num = 3.14159;
cout << "原数:" << num << endl;
cout << "保留两位有效数字:" << endl;
//{
cout <<setprecision(2) << num << endl; //3.1
//}
cout << "保留三位有效数字:" << endl;
//{
cout << setprecision(3) << num << endl; //3.14
//}
cout << "保留四位有效数字:" << endl;
//{
cout << setprecision(4) << num << endl; //3.142
//}
cout << "保留五位有效数字:" << endl;
//{
cout << setprecision(10) << num << endl; //3.14159 注意这里并不会补零
//}
system("pause");
return 0;
}
结果:
原数:3.14159
保留两位有效数字:
3.1
保留三位有效数字:
3.14
保留四位有效数字:
3.142
保留五位有效数字:
3.14159
补充:占位输出
setw(n):占n位
setfill(‘填充字符’):