In: Computer Science
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 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.
Input Validation: Do not accept a number less than 1 for the number of years. Do not accept negative numbers for the monthly rainfall.
Please post the program working as well. Thank you
Solution
Code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int numYears=0;
const int MONTHS=12;
float totalRainfall=0.0f;
float rainfall=0.0f;
float avgRainfall=0.0f;
cout<<"Please enter number of years"<<endl;
cin>>numYears;
while(numYears<1)
{
cout<<"Number of years must be at least 1. Please re
enter";
cin>>numYears;
}
for(int i=1;i<=numYears;i++)
{
for(int months=1;months<=MONTHS;months++)
{
cout<<"Please enter the rainfall for "<<months<<"
month: ";
cin>>rainfall;
while(rainfall<0)
{
cout<<"The rainfall cannot be negative number. Please
reenter:";
cin>>rainfall;
}
totalRainfall += rainfall;
}
}
cout<<"\nNumber of months: " <<numYears *
MONTHS<<endl;
cout<<"Total rainfall:
"<<setprecision(2)<<fixed<<totalRainfall<<"
inches."<<endl;
cout<<"Average rainfall:
"<<setprecision(2)<<fixed<<totalRainfall/(numYears
* MONTHS)<<" inches";
return 0;
}
Screenshot and Output
---
programming language not mentioned, i solved in c++
if you have any doubt, please mention it, love to help
all the best
please upvote