Skip to content

Instantly share code, notes, and snippets.

@Fiona-J-W
Last active August 29, 2015 14:14
Show Gist options
  • Save Fiona-J-W/25c8c1d436e1437d66e7 to your computer and use it in GitHub Desktop.
Save Fiona-J-W/25c8c1d436e1437d66e7 to your computer and use it in GitHub Desktop.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
float read_rain(unsigned month);
float get_total(const std::vector<float>& data);
unsigned find_min(const std::vector<float>& data);
unsigned find_max(const std::vector<float>& data);
const int month_count = 12;
// there isn't a problem with a global array IF it is CONSTANT
const std::vector<std::string> month_names = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int main() {
std::vector<float> rains;
for (unsigned i = 0; i < month_count; i++) {
rains.push_back(read_rain(i));
}
float total = get_total(rains);
get_total(rains);
std::cout << "The total rainfall was: " << total << "\n"
<< "The average monthly rainfall was: " << total / month_count << "\n";
unsigned min = find_min(rains);
std::cout << month_names[min] << " had the least rain at: " << rains[min] << "\n";
unsigned max = find_max(rains);
std::cout << month_names[max] << " had the most rain at: " << rains[max] << "\n";
}
float read_rain(unsigned month) {
std::cout << "Amount of rain for " << month_names[month] << ": ";
float rain = 0;
std::cin >> rain;
std::cout << "\n";
while (rain < 0) {
std::cout << "Invalid Number, please enter again:\n";
std::cin >> rain;
}
return rain;
}
float get_total(const std::vector<float>& data) {
float total = 0;
for (auto datum: data) {
total += datum;
}
return total;
}
unsigned find_min(const std::vector<float>& data) {
float min = data.front();
unsigned min_index = 0;
for (unsigned i = 1; i < month_count; ++i) {
if (data.at(i) < min) {
min = data.at(i);
min_index = i;
}
}
return min_index;
}
unsigned find_max(const std::vector<float>& data) {
float max = data.front();
unsigned max_index = 0;
for (unsigned i = 1; i < month_count; ++i) {
if (data.at(i) > max) {
max = data.at(i);
max_index = i;
}
}
return max_index;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment