read random hour + temperature pairs [fahrenheite + celsius indicator] and calculate mean and median values

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

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

#include "std_lib_facilities.h"

struct Reading {
int hour;
double temperature;
char suffix;
Reading(int h, double t, char s) :hour(h), temperature(t), suffix(s) {}
};

ostream& operator<<(ostream& os, Reading& _temps) {
os << _temps.hour << " " << _temps.temperature << " " << _temps.suffix << endl;
return os;
}

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 = "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;
char s;
while (ist >> h >> t >> s) {
if (s == ‘c’) {
t = (t * (9.0 / 5.0)) + 32;
s = ‘f’;
}
temps.push_back(Reading{ h, t, s });
}
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);

for (Reading i : temps) {
cout << i;
}

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: 78.444 median: 63.9
Please enter a character to exit
Input-File raw_temps.txt:
0 78 c
1 1 c
2 72 c
3 65 c
4 49 f
5 48 c
6 67 f
7 20 c
8 76 f
9 36 c
10 15 c
11 16 c
12 34 c
13 37 f
14 79 f
15 60 f
16 15 c
17 1 c
18 84 c
19 79 f
20 0 c
21 86 f
22 76 c
23 73 c
0 74 f
1 22 f
2 28 f
3 30 c
4 36 c
5 0 c
6 60 f
7 78 f
8 56 c
9 51 f
10 40 f
11 52 f
12 15 f
13 47 f
14 59 f
15 82 f
16 77 c
17 46 f
18 1 c
19 0 c
20 1 c
21 2 c
22 15 c
23 36 c
0 87 c
1 29 c

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