//Marvyn Jesse De La Torre CS1A Chapter 7, pg.444, #2
//
/******************************************************************************
* CALCULATE RAINFALL
*
* This program asks the user to enter the rainfall for each month.
* It stores the amounts in an array and calculates the total and average
* rainfall. It also finds the months with the highest and lowest rainfall.
*
* INPUT
* rainfall - Rainfall amount for each month
*
* OUTPUT
* total - Total rainfall for the year
* average - Average rainfall per month
* highestMonth - Month with the most rainfall
* lowestMonth - Month with the least rainfall
******************************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
using namespace std;
int main()
{
const int MONTHS = 12;
double rainfall[MONTHS];
double total = 0.0;
int highestMonth = 0;
int lowestMonth = 0;
// List of month names.
string months[MONTHS] =
{
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
// Get the rainfall amount for each month.
for (int i = 0; i < MONTHS; i++)
{
cout << "Enter rainfall for " << months[i] << ": ";
cin >> rainfall[i];
// Make sure the rainfall amount is valid.
while (cin.fail() || rainfall[i] < 0)
{
cout << "Invalid amount. Enter a positive number: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin >> rainfall[i];
}
total += rainfall[i];
}
// Find the months with the highest and lowest rainfall.
for (int i = 1; i < MONTHS; i++)
{
if (rainfall[i] > rainfall[highestMonth])
{
highestMonth = i;
}
if (rainfall[i] < rainfall[lowestMonth])
{
lowestMonth = i;
}
}
// Display the rainfall results.
cout << fixed << setprecision(2);
cout << "\nRainfall Statistics\n";
cout << "--------------------\n";
cout << "Total rainfall: " << total << " inches\n";
cout << "Average rainfall: " << total / MONTHS << " inches\n";
cout << "Month with the most rainfall: "
<< months[highestMonth] << " ("
<< rainfall[highestMonth] << " inches)\n";
cout << "Month with the least rainfall: "
<< months[lowestMonth] << " ("
<< rainfall[lowestMonth] << " inches)\n";
return 0;
}