Printing the floating number in system default, scientific and fixed format C++ program sample

 

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: Displaying the floating number in system default, scientific and fixed format in C++ programming

To show: How to display the floating number in system default, scientific and fixed format in C++ programming

 

// displaying floating number in system default, scientific and fixed format

#include <iostream>

using namespace std;

 

void main(void)

{

double p = 0.000654321, q = 9.8765e3;

 

cout<<"Declared variables\n"

<<"------------------\n"

<<"0.000654321"<<"\n"<<"9.8765e3"<<"\n\n";

cout<<"Default format:\n"

<<"---------------\n"

<<p<<"\t"<<q<<"\n"<<endl;

cout.setf(ios::scientific,ios::floatfield);

cout<<"Scientific format:\n"

<<"------------------\n"

<<p<<"\t"<<q<<"\n";

cout.unsetf(ios::scientific);

cout<<"\nDefault format after unsetf:\n"

<<"----------------------------\n"

<<p<<"\t"<<q<<endl;

cout.setf(ios::fixed,ios::floatfield);

cout<<"\nIn fixed format:\n"

<<"----------------\n"

<<p<<"\t"<<q<<endl;

return;

}

 

Output example:

 

Declared variables

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

0.000654321

9.8765e3

Default format:

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

0.000654321 9876.5

Scientific format:

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

6.543210e-004 9.876500e+003

Default format after unsetf:

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

0.000654321 9876.5

In fixed format:

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

0.000654 9876.500000

Press any key to continue . . .

 

 

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