# Exercise 3-2

a guest
May 21st, 2012
317
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /*
2.  * This program uses the following method for calculating quartiles:
3.  * http://en.wikipedia.org/wiki/Quartile#Method_1
4.  */
5.
6. #include <algorithm>
7. #include <iomanip>
8. #include <ios>
9. #include <iostream>
10. #include <string>
11. #include <vector>
12.
13. using std::cin;
14. using std::cout;
15. using std::endl;
16. using std::setprecision;
17. using std::sort;
18. using std::streamsize;
19. using std::string;
20. using std::vector;
21.
22. int main()
23. {
24.     // retrieve data from user
25.     cout << "Enter values, followed by end-of-file: ";
26.
27.     vector<double> data;
28.     double x;
29.
30.     // invariant: data contains all the values read so far
31.     while (cin >> x)
32.     data.push_back(x);
33.
34.     // check that data is not empty
35.     typedef vector<double>::size_type vec_sz;
36.     vec_sz size = data.size();
37.     if (size == 0) {
38.     cout << endl << "You must enter some values. Try again." << endl;
39.     return 1; // ERROR
40.     }
41.
42.     // sort the data
43.     sort(data.begin(), data.end());
44.
45.     /*
46.      * There will be mid elements in both upper and lower sublists (assuming the median is not included):
47.      * lower_half_size = upper_half_size = mid
48.      */
49.     vec_sz mid = size / 2;
50.     vec_sz lower_mid = mid / 2;
51.     vec_sz upper_mid;
52.     double median, lower_quartile, upper_quartile;
53.
54.     // determine midpoints of median and upper/lower halves
55.     if (size % 2 == 0) {
56.     median = (data[mid] + data[mid-1]) / 2;
57.     upper_mid = 3 * mid / 2; // mid + (mid/2); median is not a datum so mid is beginning of list
58.     } else {
59.     median = data[mid];
60.     upper_mid = (3 * mid / 2) + 1; // median should not be included
61.     }
62.
63.     // calculate median
64.     median = (size % 2 == 0) ? (data[mid] + data[mid-1]) / 2 : data[mid];
65.
66.     // calculate lower and upper quartiles
67.     if (mid % 2 == 0) {
68.     lower_quartile =  (data[lower_mid] + data[lower_mid-1]) / 2;
69.     upper_quartile = (data[upper_mid] + data[upper_mid-1]) / 2;
70.     } else {
71.     lower_quartile = data[lower_mid];
72.     upper_quartile = data[upper_mid];
73.     }
74.
75.     // write out quartiles
76.     streamsize prec = cout.precision();
77.     cout << "The quartiles are " << setprecision(3) << lower_quartile << ", " << median << ", and "
78.      << upper_quartile << "." << setprecision(prec) << endl;
79.     return 0;
80. }