Hi there! My code seems to run fine with the one exception of not showing January as the month with least rainfall. Here are what the challenge specifies:
Write a program that lets the user enter the total rainfall for each of 12 months (starting with January) into an array of
doubles.
Once the user has entered the rainfall for all the months, the program should calculate and display (in this order):
The total rainfall for the year
The average monthly rainfall
The months with the highest and lowest amounts
Note:
Numeric values should be displayed using default precision. Do not use format specifiers to specify precision.
Input Validation:
Do not accept a negative number for any of the monthly rainfall amounts. If the user enters a negative value, the program should print the following string (exactly as it is shown here):
"invalid data (negative rainfall) -- retry"
and then immediately read the value again as input.
The following sample run shows how your program's output must appear. The user's input is shown in bold.
Here's what I've got so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
const int MONTHS = 12;
string name[MONTHS] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
int i = 0;
double rainfall[MONTHS];
double total = 0, avg = 0, highRain = 0, lowRain = 0;
string highMonth;
string lowMonth;
for (int i = 0; i < MONTHS; i++)
{
cout << "Enter rainfall for " << name[i] << ": " << endl;
cin >> rainfall[i];
while (rainfall[i] < 0)
{
cout << "invalid data (negative rainfall) -- retry" << endl;
cin >> rainfall[i];
}
total += rainfall[i];
}
avg = total / 12;
highRain = rainfall[0];
for (int i = 1; i < MONTHS; i++)
{
if (rainfall[i] > highRain)
{
highMonth = name[i];
highRain = rainfall[i];
}
}
lowRain = rainfall[0];
for (int i = 1; i < MONTHS; i++)
{
if (rainfall[i] < lowRain)
{
lowMonth = name[i];
lowRain = rainfall[i];
}
}
cout << "Total rainfall: " << total << endl;
cout << "Average : " << avg << endl;
cout << "Least rainfall in: " << lowMonth << endl;
cout << "Most rainfall in: " << highMonth << endl;
return 0;
}
|
I appreciate anyone that might be able to help!