Archive for June 1st, 2009

How to set precision in C++

June 1, 2009

In C++, you can use the ‘precision’ function to set the precision of the output. The function ‘precision’ is present in the header file ‘iostream.h’. The following,


will have totally print ‘n’ d igits in the output with the decimal point in between(say ‘x’ before the decimal and ‘n-x’ after the decimal. The value of x will depend on the result). For example, if n = 4, the result is

0.2727 for 3/11, and
1.272 for 14/11

The example illustrated below provide a clear guidance on how to use the precision function. The Problem is to find the sum of ‘n’ numbers and then print the output in a single line.


using namespace std;

int main()
double a,s=0;
while( cin >> a )
s += a;
return 0;

%d bloggers like this: