In: Computer Science
Write a C++ 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):
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.
Use an Array for saving the Month names and values.
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.
NOTE: Decimal values should be displayed using default precision,
i.e. do not specify precision.
Sample Output:
Enter rainfall for January: 1 Enter rainfall for February: 2 Enter rainfall for March: 3 Enter rainfall for April: 4 Enter rainfall for May: 5 Enter rainfall for June: 6 Enter rainfall for July: 7 Enter rainfall for August: 8 Enter rainfall for September: 9 Enter rainfall for October: 10 Enter rainfall for November: 11 Enter rainfall for December: 12 Total rainfall: 78 Average rainfall: 6.5 Least rainfall in: January Most rainfall in: December
#include <iostream>
using namespace std;
int main()
{
// Use an Array for saving the Month names and values.
string months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
double rainfall[12];
// average, max and min, total rainfall
double average = 0, total = 0;
int max = 0, min = 0;
for (int i = 0; i < 12; i++)
{
cout << "Enter rainfall for " << months[i] << ": ";
cin >> rainfall[i];
// When a negative value is entered,
if (rainfall[i] < 0)
{
cout << "invalid data (negative rainfall) -- retry";
// attempts to reread the value.
i--;
}
else
{
// compute min
if (rainfall[min] > rainfall[i])
min = i;
// compute max
if (rainfall[max] < rainfall[i])
max = i;
// compute total
total += rainfall[i];
}
}
// compute average
average = total / 12;
cout << "Total rainfall: " << total << endl;
cout << "Average rainfall: " << average << endl;
cout << "Least rainfall in: " << months[min] << endl;
cout << "Most rainfall in: " << months[max] << endl;
}
.
Output:
.