Using the setprecision(), precision() methods in C++ programming to print float/double in the desired precisions

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the setprecision(), precision() methods in C++ programming to print float/double in the desired precisions

To show: How to control the float/double printing precisions using setprecision() and precision() methods in C++ programming

 

// using precision() and setprecision()

#include <iostream>

#include <iomanip>

#include <cmath>

using namespace std;

 

void main(void)

{

double theroot = sqrt(11.55);

 

cout<<"Square root of 11.55 with various"<<endl;

cout<<" precisions()"<<endl;

cout<<"---------------------------------"<<endl;

cout<<"Using 'precision()':"<<endl;

for(int poinplace=0; poinplace<=8; poinplace++)

{

cout.precision(poinplace);

cout<<theroot<<endl;

}

cout<<"\nUsing 'setprecision()':"<<endl;

for(int poinplace=0; poinplace<=8; poinplace++)

cout<<setprecision(poinplace)<<theroot<<endl;

}

 

Output example:

 

Square root of 11.55 with various

precisions()

---------------------------------

Using 'precision()':

3.39853

3

3.4

3.4

3.399

3.3985

3.39853

3.398529

3.3985291

Using 'setprecision()':

3.39853

3

3.4

3.4

3.399

3.3985

3.39853

3.398529

3.3985291

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index