read hour + temperature pairs and calculate mean and median temperature

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 10 Exercise 3
Using std_lib_facilities.h by Bjarne Stroustrup.

[code language=”cpp”]
// Philipp Siedler
// Bjarne Stroustrup’s PPP
// Chapter 10 Exercise 3

#include "std_lib_facilities.h"

struct Reading {
int hour;
double temperature;
};

struct Stats {
double mean;
double median;
};

ostream& operator<<(ostream& os, Stats _stats) {
os << "mean: " << _stats.mean << " median: " << _stats.median << endl;
return os;
}

vector<Reading> temps;

string iname = "output/raw_temps.txt";
ifstream ist(iname);

void read_file(vector<Reading>& _temps, string _file_name) {
if (!ist) { error("Could not open file", _file_name); }
cout << "Reading file." << endl;
int h;
double t;
while (ist >> h >> t) {
temps.push_back(Reading{ h,t });
}
cout << "Done!" << endl;
}

Stats calculate_stats(vector<Reading>& _temps) {
cout << "Calculating mean and median." << endl;
double sum = 0;
double mean;
double median;
int size = int(_temps.size());

for (int i = 0; i < size; i++) {
sum += _temps[i].temperature;
}
mean = sum / size;

vector<double> sorted_temps;
for (int i = 0; i < size; i++) {
sorted_temps.push_back(_temps[i].temperature);
}
sort(sorted_temps);

if (size % 2 == 0) {
median = (sorted_temps[size / 2] + sorted_temps[(size / 2) – 1]) / 2;
}
else {
median = sorted_temps[(size – 1) / 2];
}
return Stats{ mean, median };
}

int main()
try
{
read_file(temps, iname);
cout << calculate_stats(temps);

keep_window_open();

}
catch (runtime_error e) {
cout << e.what() << endl;
keep_window_open();
}
catch (…) {
cout << "Exiting" << endl;
keep_window_open();
}
[/code]

Output:
Reading file.
Done!
Calculating mean and median.
mean: 47.64 median: 48.5
Please enter a character to exit
Input-File raw_temps.txt:
0 78
1 14
2 1
3 15
4 72
5 20
6 65
7 54
8 49
9 67
10 48
11 73
12 67
13 49
14 20
15 42
16 76
17 38
18 36
19 40
20 15
21 87
22 16
23 51
0 34
1 63
2 37
3 48
4 79
5 41
6 60
7 21
8 15
9 51
10 1
11 41
12 84
13 13
14 79
15 38
16 0
17 16
18 86
19 88
20 76
21 50
22 73
23 77
0 74
1 44

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply

Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124