Monday, September 5, 2011

How to Set Precision

There are quite some problems in which the output is required to be in decimal format. Making 1.00 from 1 could be done by a lot of other ways but none is as good and short as using setprecision(); Just include “iomanip” in your code and you are ready to use this manipulator.

Example Source Code:
#include<iostream>
#include<iomanip>
using namespace::std;
int main(void)
{
double number;
cout<<”Enter the integer: ”;
cin>>number;
cout<<showpoint<<fixed;
cout<<setprecision(2);
cout<<”You entered: ”<<number;
return 0;
}

Here:


Setprecision(int n) is used to set the required precision which you pass as an argument to the manipulator; See that it is 2 in the above program, you can change it. However this manipulator will only work for the upcoming cout statement. For setting the precision of next value, you again need to use this manipulator or you can use ‘fixed’ for convenience.

fixed(Optional) is used to fix the precision i.e throughout your program the precision will remain the same once you set it with setprecision.

Showpoint(Optional) forces the program to show the decimal point and the decimal part of the number whose decimal part is 0. e.g 1 may not show up as 1.00 if you do not instruct the computer to show the point by using this manipulator.

0 response(s):

Respond to this Post

Your participation is appriciated...