// Torrez, Elaine CS1A Chapter 5, P. 298, #3
/*******************************************************************************************
*
* AVERAGE RAINFALL
* ________________________________________________________________________________________
* This program calculates the average rainfall over a given number of years.
* The user enters the number of years, and for each year, the rainfall (in inches)
* for each of the 12 months is entered. The program then calculates and displays
* the total number of months, the total inches of rainfall, and the average rainfall
* per month for the entire period.
* ________________________________________________________________________________________
*
* INPUT:
* years : number of years
* rainfall : monthly rainfall in inches
*
* OUTPUT:
* totalMonths : total number of months (years * 12)
* totalRainfall : total rainfall in inches for the period
* averageRainfall: average rainfall per month
*
*******************************************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
/***** VARIABLE DECLARATIONS *****/
int years; // Number of years
int totalMonths; // Total number of months
double rainfall; // Rainfall for one month
double totalRainfall; // Total rainfall for all months
double averageRainfall; // Average rainfall per month
/***** INPUT SECTION *****/
cout << "Enter the number of years: ";
cin >> years;
// Validate number of years (must be at least 1)
while (years < 1)
{
cout << "Invalid. Number of years must be at least 1. Try again: ";
cin >> years;
}
totalRainfall = 0.0;
totalMonths = 0;
/***** PROCESSING SECTION *****/
for (int year = 1; year <= years; year++)
{
cout << "\nYear " << year << endl;
for (int month = 1; month <= 12; month++)
{
cout << " Enter rainfall (in inches) for month " << month << ": ";
cin >> rainfall;
// Validate rainfall (cannot be negative)
while (rainfall < 0)
{
cout << " Invalid. Rainfall cannot be negative. Try again: ";
cin >> rainfall;
}
totalRainfall += rainfall;
totalMonths++;
}
}
averageRainfall = totalRainfall / totalMonths;
/***** OUTPUT SECTION *****/
cout << fixed << setprecision(2);
cout << "\nNumber of months: " << totalMonths << endl;
cout << "Total inches of rainfall: " << totalRainfall << endl;
cout << "Average rainfall per month: " << averageRainfall << " inches" << endl;
return 0;
}