Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * This program uses the following method for calculating quartiles:
- * http://en.wikipedia.org/wiki/Quartile#Method_1
- */
- #include <algorithm>
- #include <iomanip>
- #include <ios>
- #include <iostream>
- #include <string>
- #include <vector>
- using std::cin;
- using std::cout;
- using std::endl;
- using std::setprecision;
- using std::sort;
- using std::streamsize;
- using std::string;
- using std::vector;
- int main()
- {
- // retrieve data from user
- cout << "Enter values, followed by end-of-file: ";
- vector<double> data;
- double x;
- // invariant: data contains all the values read so far
- while (cin >> x)
- data.push_back(x);
- // check that data is not empty
- typedef vector<double>::size_type vec_sz;
- vec_sz size = data.size();
- if (size == 0) {
- cout << endl << "You must enter some values. Try again." << endl;
- return 1; // ERROR
- }
- // sort the data
- sort(data.begin(), data.end());
- /*
- * There will be mid elements in both upper and lower sublists (assuming the median is not included):
- * lower_half_size = upper_half_size = mid
- */
- vec_sz mid = size / 2;
- vec_sz lower_mid = mid / 2;
- vec_sz upper_mid;
- double median, lower_quartile, upper_quartile;
- // determine midpoints of median and upper/lower halves
- if (size % 2 == 0) {
- median = (data[mid] + data[mid-1]) / 2;
- upper_mid = 3 * mid / 2; // mid + (mid/2); median is not a datum so mid is beginning of list
- } else {
- median = data[mid];
- upper_mid = (3 * mid / 2) + 1; // median should not be included
- }
- // calculate median
- median = (size % 2 == 0) ? (data[mid] + data[mid-1]) / 2 : data[mid];
- // calculate lower and upper quartiles
- if (mid % 2 == 0) {
- lower_quartile = (data[lower_mid] + data[lower_mid-1]) / 2;
- upper_quartile = (data[upper_mid] + data[upper_mid-1]) / 2;
- } else {
- lower_quartile = data[lower_mid];
- upper_quartile = data[upper_mid];
- }
- // write out quartiles
- streamsize prec = cout.precision();
- cout << "The quartiles are " << setprecision(3) << lower_quartile << ", " << median << ", and "
- << upper_quartile << "." << setprecision(prec) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement