Wednesday 10 March 2010

Fixed form, Scientific form and Precision setting for floating point numbers

Sometimes we want to output the floating point numbers in fixed or scientific form and sometimes with fixed precision so as to align all the output. The following program is an example to demonstrate that:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows how to output floating point numbersin fixed and
#include<iostream>

using namespace
std;

int
main()
{

float
number = 123.456;

cout << "number in fixed form = " << number << endl; //default is fixed
cout << "number in scientific form = " << scientific << number << endl;
cout.precision(2);
cout << "number in fixed form with precision 2 = " << fixed << number << endl; //here the format was scientific
cout.precision(3);
cout << "number in fixed form with precision 3 = " << number << endl;
cout.precision(4);
cout << "number in fixed form with precision 4 = " << number << endl;
cout.precision(5);
cout << "number in fixed form with precision 5 = " << number << endl;

return
0;
}






The output is as follows:

2 comments:

  1. Thank you Zahid for sharing this information.
    I did not know about scientific keyword in C++.
    If possible can you write scientific work in different color - I did not understand that part of program unless I copied and compiled this program.

    ReplyDelete
  2. GCC gives same output -
    number in fixed form = 123.456
    number in scientific form = 1.234560e+02
    number in fixed form with precision 2 = 123.46
    number in fixed form with precision 3 = 123.456
    number in fixed form with precision 4 = 123.4560
    number in fixed form with precision 5 = 123.45600

    (I tested this using cygwin, GCC 3.2)

    ReplyDelete