Average Rainfall Write a program that uses nested loops to collect data and calc
ID: 3757653 • Letter: A
Question
Average Rainfall 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 twelve 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.Explanation / Answer
#include<iostream>
#include<vector>
using namespace std;
int getyears() {
int years;
cout << "Enter how many years required" << ' ';
cin >> years;
return years;
}
vector<double> getdata(int years) {
vector<double> rainfall;
int i;
int j;
double input;
for(i = 1; i <= years; i = i + 1) {
for(j = 1;j <= 12; j = j + 1) {
cout << "Enter rainfall for the year " << j << "th month of the " << i
<< "th year." << ' ';
cin >> input;
rainfall.push_back(input);
}
}
return rainfall;
}
int numberofmonths(vector<double> rainfall) {
int months = rainfall.size();
return months;
}
double totalinches(vector<double> rainfall) {
double sum;
for(vector<double>::iterator i = rainfall.begin(); i != rainfall.end(); ++i)
{
sum = sum + *i;
}
return sum;
}
double getaverage(vector<double> rainfall, double inches) {
double average = inches / rainfall.size();
return average;
}
bool validate_input(int years, vector<double> rainfall) {
if(years < 1) {
cout << "Error: did not enter at least one year." << ' ';
return false;
}
else {
for(vector<double>::iterator i = rainfall.begin(); i != rainfall.end(); ++i) {
if(*i < 0) {
cout << "Error: entered a negative number for rainfall." << ' ';
return false;
}
}
}
return true;
}
int main() {
int years = getyears();
vector<double> rainfall = getdata(years);
int months = numberofmonths(rainfall);
double inches = totalinches(rainfall);
double average = getaverage(rainfall, inches);
if(!validate_input(years, rainfall)) return 0;
cout << "Number of months: " << months << " months" <<' '
<< "Number of inches: " << inches << " inches" << ' '
<< "Average rainfall: " << average << " inches" << ' ';
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.