C++中的格式设置区别

今天使用C++编程练习时遇到了一个小问题:包含头文件iomanip文件后,在标准输出流中使用setprecision函数指定了输出数据的精度。没有预料到setprecision函数会影响到后面输出流的精度。

查阅了些C++的资料,下面总结一下C++设定输出格式的几种方式:

(1) 使用cout对象的width方法,如: cout.width(20);
(2) 使用<iomanip>里面的函数设置输出的行宽。

<iomanip>中总共有六个成员函数:
setw //指定显示区域宽度 --- [color=red]不影响后续的输出流![/color]
setprecision //指定浮点数的精度 --- [color=red]影响后续的输出流![/color]
setfill //在右对齐方式显示时,设定填充的符号
setbase //设置输出的基数,例如要输出八进制数时设置setbase(8)
setiosflags //设定标志位
resetiosflags //清除设定的标志位

其中,setiosflags和resetiosflags是一对函数,它们由于改变一些flag的值。


#include <iostream>
#include <cstdlib>
#include <iomanip>

using namespace std;

class Rectangle
{
public :
Rectangle(float width,float hight);
double GetArea();
float GetWidth();
float GetHight();
~Rectangle();
private :
float width;
float hight;
};

Rectangle::Rectangle(float width,float hight)
{
this->width=width;
this->hight=hight;
}

Rectangle::~Rectangle()
{
cout<<"Resource have been release!!"<<endl;
cout<<"width ----------->"<<this->GetWidth()<<endl; //受到setprecision函数的影响
cout<<"hight ----------->"<<this->GetHight()<<endl; //受到setprecision函数的影响
}

double Rectangle::GetArea()
{
return this->width * this->hight;
}

float Rectangle::GetWidth()
{
return this->width;
}

float Rectangle::GetHight()
{
return this->hight;
}

int main(int argc,char * args[])
{
{
Rectangle rectangle(12.29,18.12);
cout<<"The width of the rectangle : "<<rectangle.GetWidth()<<endl;
cout<<"The hight of the rectangle : "<<rectangle.GetHight()<<endl;
cout<<"The Area of the rectangle :"<<setprecision(8)<<rectangle.GetArea()<<endl;
}
system("pause");
return EXIT_SUCCESS;
}


运行结果:
[img]result.JPG[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值