SOURCE FILE: 02RainFall.cpp


//******************************************************************
// Rainfall program
// This program inputs 12 monthly rainfall amounts from a
// recording site and computes the average monthly rainfall.
// This process is repeated for as many recording sites as
// the user wishes.
//******************************************************************

#include <iostream>
#include <iomanip>    // For setprecision()

using namespace std;

void Get12Amounts( float& );
void GetOneAmount( float& );
void GetYesOrNo( char& );

int main()
{
    float sum;		 // Sum of 12 rainfall amounts
    char  response;	 // User response ('y' or 'n')

    cout << fixed << showpoint		      // Set up floating pt.
	 << setprecision(2);		      //   output format

    do
    {
	Get12Amounts(sum);
	cout << endl << "Average rainfall is " << sum / 12.0
	     << " inches" << endl << endl;
	cout << "Do you have another recording site? (y or n) ";
	GetYesOrNo(response);
    } while (response == 'y');

    return 0;
}

//******************************************************************

void Get12Amounts( /* out */ float& sum )   // Sum of 12 rainfall
					    // amounts

// Inputs 12 monthly rainfall amounts, verifying that
// each is nonnegative, and returns their sum

// Postcondition:
//     12 rainfall amounts have been read and verified to be
//     nonnegative
//  && sum == sum of the 12 input values

{
    int	  count;       // Loop control variable
    float amount;      // Rainfall amount for one month
    sum = 0;

    for (count = 1; count <= 12; count++)
    {
	cout << "Enter rainfall amount " << count << ": ";
	GetOneAmount(amount);
	sum = sum + amount;
    }
}

//******************************************************************

void GetYesOrNo( /* out */ char& response )   // User response char

// Inputs a character from the user and, if necessary,
// repeatedly prints an error message and inputs another
// character if the character isn't 'y' or 'n'

// Postcondition:
//     response has been input (repeatedly, if necessary, along
//     with output of an error message)
//  && response == 'y' or 'n'

{
    do
    {
	cin >> response;
	if (response != 'y' && response != 'n')
	    cout << "Please type y or n: ";
    } while (response != 'y' && response != 'n');
}

//******************************************************************

void GetOneAmount( /* out */ float& amount )   // Rainfall amount
					       // for one month

// Inputs one month's rainfall amount and, if necessary,
// repeatedly prints an error message and inputs another
// value if the value is negative

// Postcondition:
//     amount has been input (repeatedly, if necessary, along
//     with output of an error message)
//  && amount >= 0.0

{
    do
    {
	cin >> amount;
	if (amount < 0.0)
	    cout << "Amount cannot be negative. Enter again: ";
    } while (amount < 0.0);
}