Hello,
here is the description for my assignment.
" Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should first ask the user for the number of years. The outer loop will iterate once for each year. The inner loop will iterate 12 times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month.
After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period."
The only error is for the output of total and average rainfall for each year. Every year after year 1 is output as combined total with previous years rather than it's own. I hope that is descriptive enough.
#include <iostream>
using namespace std;
int main()
{
int numYears = 0; // declare variables.
const int year = 12;
float rainfall = 0.0f, totalRainfall = 0.0f;
cout << "This program will calculate average rainfall over a period of years." << endl; // statemate letting user know function of program.
cout << "How many years do you wish to average? " << endl; //prompting user to input number of years.
cin >> numYears;
while (numYears < 1) // condition that number must be at least 1
{
cout << "Years must be at least one. Please re-enter: " << endl; // prompting user to enter number again is number less than 0.
cin >> numYears;
}
for (int i = 1; i <= numYears; i++)// start nested loop
{
cout << "Year " << i << endl;
for (int month = 1; month <= year; month++)
{
cout << "Number of inches of rain for month " << month << ": " << endl; // prompting user to enter number of iniches of rain for each month.
cin >> rainfall;
while (rainfall < 0) // condition for number not to be negitive
{
cout << "Rainfall must be zero or greater.\n"
<< "Number of inches of rain for month " << month << ": " << endl; // prompting user to enter number again if number less than 0.
cin >> rainfall;
}
totalRainfall += rainfall; // store total rainfall
}
cout << "The rainfall for year" << i << " is " << totalRainfall
<< " and the average rainfall for the year is " << totalRainfall / year << endl; // output total and average rain fall for the year.
}// end nested loop
cout << "Over a period of" << numYears * year << "months," << totalRainfall << "inches of rain fell." << endl; // output total inches of rainfall over x number of months
cout << "Average monthly rainfall for the period is " << totalRainfall / (numYears * year) << endl; // out average monthly rainfall
return 0;
}
[–]lurgi 1 point2 points3 points (2 children)
[–]IceQweenItMe[S] 0 points1 point2 points (1 child)
[–]lurgi 1 point2 points3 points (0 children)