前置补0
题目中算时间,要求格式化输出时间,如果时间不够10,会在前面补0。
需要头文件iomanip
setw()
设置输出宽度,作用范围仅有一次。
setfill()
设置要填充的字符,默认空格,作用范围是直到下一个setfill才更改
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int hour = 3;
int minute = 2;
int second = 0;
cout<<setw(2)<<setfill('0')<<hour<<':'
<<setw(2)<<minute<<':'
<<setw(2)<<second;
}
最终输出结果为03:02:00
保留有效位
setprecision()
设置要保留的位数
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
float a = 123.47678;
cout<<a<<" "<<setprecision(4)<<a<<endl;
}
输出结果123.477 123.5
保留小数
使用流操作符fixed
与setprecision()
,它们将指定浮点数字的小数点后要显示的位数,而不是要显示的总有效数位数。
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
float a = 123.47678;
cout << fixed << setprecision(2);
cout << a;
}
输出结果 123.48
取整
引入cmath
头文件,ceil()
向上取整,floor()
向下取整,round()
四舍五入
#include<iostream>
#include<cmath>
using namespace std;
int main() {
float a = 123.47678;
cout << "向上取整:" << ceil(a) << endl;
cout << "向下取整:" << floor(a) << endl;
cout << "四舍五入:" << round(a) << endl;
}
/*
输出结果:
向上取整:124
向下取整:123
四舍五入:123
*/