C++格式化输出

前置补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

保留小数

使用流操作符fixedsetprecision(),它们将指定浮点数字的小数点后要显示的位数,而不是要显示的总有效数位数。

#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
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lum1n0us

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值