Rainfall Statistics Write a program that lets the user enter the total rainfall
ID: 3641753 • Letter: R
Question
Rainfall StatisticsWrite a program that lets the user enter the total rainfall for each of 12 months (starting with January) into an array of doubles. The program should calculate and display (in this order):
the total rainfall for the year,
the average monthly rainfall,
and the months with the highest and lowest amounts.
Months should be expressed as English names for months in the Gregorian calendar, i.e.: January, February, March, April, May, June, July, August, September, October, November, December.
Input Validation: Do not accept negative numbers for monthly rainfall figures. When a negative value is entered, the program outputs "invalid data (negative rainfall) -- retry" and attempts to reread the value.
Prompts And Output Labels: Decimal values should be displayed using default precision, i.e. do not specify precision. Each item read should be prompted for by a string of the form "Enter rainfall for MONTH:" where MONTH is "January" or "February" or ... or "December". The output should be of the form:
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int main() {
string months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
double rainfall[12] = {-1};
double total = 0;
int min = 0;
int max = 0;
for(int i = 0; i < 12; ++i) {
cout << "Enter rainfall for " << months[i] << ": ";
cin >> rainfall[i];
while(rainfall[i] < 0) {
cout << "Invalid data (Negative rainfall) -- retry" << endl;
cout << "Enter rainfall for " << months[i] << ": ";
cin >> rainfall[i];
}
total += rainfall[i];
if(rainfall[i] < rainfall[min]) {
min = i;
}
else if(rainfall[i] > rainfall[max]) {
max = i;
}
}
cout << "Total rainfall: " << total << endl;
double average = total / 12.0;
cout << "Average monthly rainfall: " << average << endl;
cout << "Least rainfall in " << months[min] << endl;
cout << "Most rainfall in " << months[max] << endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.