读书人

C++中的格式设立区别

发布时间: 2012-12-21 12:03:49 作者: rapoo

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

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

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

<iomanip>中总共有六个成员函数:
setw //指定显示区域宽度 --- 不影响后续的输出流!
setprecision //指定浮点数的精度 --- 影响后续的输出流!
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;}


运行结果:


读书人网 >C++

热点推荐