C++ 格式化输出

C++ 格式化输出

参考 

CPLUSPLUS


1 scientific

scientific 与 fixed 的区别,请看代码,一目了然。

#include  <iostream>     // std::cout, std::fixed, std::scientific
using namespace std;
int main ()
 {
    double a = 3.1415926534;
    double b = 2006.0;
    double c = 1.0e-10;

    cout.precision(5);   //设置精度

    cout << "default:\n";
    cout << a << '\n' << b << '\n' << c << '\n';

    cout << '\n';

    cout << "fixed:\n" << fixed;    //小数位固定,为5位
    cout << a << '\n' << b << '\n' << c << '\n';

    cout << '\n';

    cout << "scientific:\n" << scientific;  //采用科学计数法
    cout << a << '\n' << b << '\n' << c << '\n';
    return 0;
}


运行结果

default:
3.1416
2006
1e-010


fixed:
3.14159
2006.00000
0.00000


scientific:
3.14159e+000
2.00600e+003
1.00000e-010

2 showpoint

showpoint   该方法是标准库中的一个,用于显示十进制的小数点。

noshowpoint正好相反。

#include <iostream>     // std::cout, std::showpoint, std::noshowpoint
using namespace std;
int main ()
{
    double a = 30;
    double b = 1000011.0;
    double pi = 3.1416;
    cout.precision (5);   //设置精度为5
    cout <<   showpoint << a << '\t' << b << '\t' << pi << '\n';  //显示小数点
    cout << std::noshowpoint << a << '\t' << b << '\t' << pi << '\n';   //不显示小数点
    return 0;
}

运行结果

30.000  1.0000e+006     3.1416
30      1e+006  3.1416


3 right 与 left

方法right 与 方法 left   用于将输出结果往左输出或者往右输出

#include <iostream>     // std::cout, std::internal, std::left, std::right
using   namespace std;
int main ()
{
    int n = -77;
    cout.width(6); cout << internal << n << '\n';
    cout.width(6); cout << left << n << '\n';  //左输出
    cout.width(6); cout << right << n << '\n';  //右输出
    return 0;
}

运行结果

-   77
-77
   -77


更多的关于格式化输出的知识可参考 CPLUSPLUS

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值