Thursday, November 11, 2010

How to Set Precision in C++

Programmers who use C++ for problem solving may need to set precision before printing floating numbers in standard output.

To display a floating number value of variable result with precision 2 (equivalent to .%2lf in scanf) use following code:
 1  cout.setf (ios::fixed, ios::floatfield);
 2  cout.setf(ios::showpoint);
 3  cout<<setprecision(2)<<result<<endl;

Here’s an example code used to solve a problem in easy volume section.

 1 /*******************************************************
 2 *  Problem Name:   Money in the bag
 3 *  Problem ID:    1002
 4 *  Occassion:    Offline Contest CSEDU Easy Volume
 5 *
 6 *  Algorithm:    
 7 *  Special Case:   
 8 *  Judge Status:   Accepted
 9 *  Author:     Saint Atique
10 *  Notes:     
11 *        
12 *******************************************************/
13 
14 #define _CRT_SECURE_NO_DEPRECATE 1
15 //#define _CRT_NONSTDC_NO_DEPRECATE 
16 
17 #include <iostream>
18 #include <cmath>
19 #include <cstring>
20 //#include <new>
21 #include <vector>
22 #include <queue>
23 #include <map>
24 #include <algorithm>
25 #include <iomanip>//for cout formatting
26 #define INF 2147483648
27 #define EPS 1e-8
28 using namespace std;
29 
30 int main() {
31  //freopen("..\\1002_in.txt", "r", stdin);
32  //freopen("..\\1002_out.txt", "w", stdout);
33 
34  double tk_amount[10] = {1000, 500, 100, 50, 20, 10, 5, 2, 1, 0.50};
35  double sum = 0;
36  int i, n;
37 
38  for (i=0; i<10; i++) {
39   cin>>n;
40   sum += n * tk_amount[i];
41  }
42 
43  cout.setf (ios::fixed, ios::floatfield);
44  cout.setf(ios::showpoint);
45  cout<<setprecision(2)<<sum<<" taka"<<endl;
46 
47  //fclose(stdin);
48  //fclose(stdout);
49  return 0;
50 }

No comments:

Post a Comment