printf和cout 数字格式化输出对比

#include <iostream>
#include <iomanip>


int main()
{
    // setfill(), setw()只生效一次
    std::cout << std::setfill('0') << std::setw(5) << 5 << ", " << 10 << ", " << 11 << '\n';    // 00005, 10, 11
    printf("%05d, %d, %d\n", 5, 10, 11);                                                        // 00005, 10, 11
    std::cout << '\n';

    // setprecision(), std::fiexed均会持久生效
    std::cout << std::setprecision(9) << 3.14159 << "," << 4.14159 << '\n';                     // 3.14159,4.14159
    printf("%.09f\n", 3.14159);                                                                 // 3.141590000
    printf("%015.09f\n", 3.14159);                                                              // 00003.141590000
    std::cout << '\n';

    std::cout << std::fixed << std::setprecision(9) << 3.14159 << ", " << 4.14159 << '\n';      // 3.141590000, 4.141590000
    std::cout << 3.14159 << ", " << 4.14159 << '\n';                                            // 3.141590000, 4.141590000
    std::cout << '\n';

    std::cout << 3.14159 << ", " << 4.14159 << '\n';                                            // 3.141590000, 4.141590000

    return 0;
}

// 总结: 1. 对比可以看出, 想要格式化输出数字, C++ cout难用、学习成本高、代码难看, 没有C的printf好用
//       2. 可以选择boost::format, 基本上具备了printf的优点, 缺点是: a. 不是标准库 b. 任然没有C#中的string.Format()好用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值