C++流操作算子

用过c语言的都知道c语言的精度格式控制非常简单容易,刚学C++也许还不懂怎么在C++中使用这些功能.这里有两个方法来使用这些功能.

变量使用:

    int n = 64;
    double d = 123.45;
    double d2 = 0.0183;

一.使用流操纵算子
首先得包含头文件
1.宽度控制

    cout << n << '#' << endl;
    //宽度控制不会影响下一个变量
    cout << setw(10) << n << '#' << endl;//默认右对齐
    cout << n << '#' << endl;

2.对齐控制

    //对齐控制会影响下面的变量对其方式
    cout << setw(10) << setiosflags(ios::left) << n << '#' << endl;//左对齐
    cout << setw(10) << n << '#' << endl;
    cout << setw(10) << setiosflags(ios::right) << n << '#' << endl;//还原成右对齐
    //cout << setw(10) << resetiosflags(ios::left) << n << '#' << endl << endl;//还原成右对齐

3.填充控制

    //填充控制会影响下面的输出
    cout << setw(10) << setfill('@') << n << '#' << endl;
    cout << setw(10) << n << '#' << endl;
    cout << setw(10) << setfill(' ') << n << '#' << endl; //还原成空格填充

4.精度控制

    //精度控制会影响下面的输出
    cout << setprecision(4) << d << endl; //控制有效数字的位数
    cout << setprecision(2) << d2 << endl;//四舍五入,而不是简单的截断
    cout << d << endl;
    cout << setiosflags(ios::fixed);      //控制小数点后面的位数
    cout << setprecision(4) << d << endl; //同样是四舍五入
    cout << setprecision(2) << d2 << endl;

5.进制控制

    cout << "dec: " << n << endl;
    cout <<"oct: "<<oct << n << endl;
    cout << "hex: " << hex << n << endl;   
    cout << n << endl;
    cout << setiosflags(ios::showbase);//显示对应进制前面的符号
    cout << "dec: " << dec <<n << endl;
    cout << "oct: " << oct << n << endl;
    cout << "hex: " << hex << n << endl;
    cout << setbase(8) << n << endl;   //进制输出
    cout << setbase(10) << n << endl;
    cout << setbase(16) << n << endl;

二.以流成员函数的方式(不用包含iomanip头文件)
1.宽度控制

    cout << n << endl;
    cout.width(10);
    cout << n << '#' << endl;

2.对齐控制

    cout << n << endl;
    cout.width(10);
    cout.setf(ios::left);
    cout << n << '#' << endl;
//  cout.width(10);
//  cout.setf(ios::right);
//  cout << n << '#' << endl;
    cout.width(10);
    cout.unsetf(ios::left);
    cout << n << '#' << endl;

3.填充控制

    cout << n <<'#'<< endl;
    cout.width(10);
    cout.fill('@');
    cout << n << '#' << endl;
    cout.width(10);
    cout << n << '#' << endl;
    cout.width(10);
    cout.fill(' ');
    cout << n << '#' << endl;

4.精度控制

    cout.precision(2);   //这个会影响下面的输出
    cout << d << endl;
    cout << d2 << endl;
    cout.setf(ios::fixed);  //控制小数点位数
    cout << d << endl;
    cout << d2 << endl;

5.进制控制

    cout.unsetf(ios::dec); //要切换进制的时候需要先去掉原先的进制
    cout.setf(ios::oct);
    cout << n << endl;

输出为100.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值