–Use 2 arrays: string months[12] and double rainfall[12] –How to read in the rai
ID: 3762052 • Letter: #
Question
–Use 2 arrays: string months[12] and double rainfall[12]
–How to read in the rainfall:
string months[] = {January, February, March, April, May, June, July, August, September, October, November, December};
for (int i=0; i<12; i++) //prompt for rain for each month
{
cout << "Enter rainfall for "<<months[i]<<":";
while (cin >> rainfall[i])
if (rainfall[i]<0)
cout <<"invalid data (negative rainfall) -- retry"<<endl;
}
–
–Write at least 2 array functions in your solution (such as int findMax() and double findAverage()).
–
int index=findMax(rainfall); //find which rainfall entry biggest
cout << months[index] << « had the most rain, which was « <<rainfall[index]<<endl;
–Debug it in MS VC++, then paste into MPL to check your solution
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int findMax(double rainfall[]) {
int maxIndex=0;
for (int i=1; i<12; i++) {
if (rainfall[i] > rainfall[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
double findAverage(double rainfall[]) {
double sum=0;
for (int i=1; i<12; i++) {
sum+=rainfall[i];
}
return sum/12.0;
}
int main()
{
string months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
double rainfall[12];
for (int i=0; i<12; i++) {
cout << "Enter rainfall for "<<months[i]<<": ";
while (true) {
cin >> rainfall[i];
if (rainfall[i]<0)
cout <<"invalid data (negative rainfall) -- retry"<<endl;
else
break;
}
}
int index=findMax(rainfall); //find which rainfall entry biggest
cout << months[index] <<" had the most rain, which was "<<rainfall[index]<<endl;
double avg = findAverage(rainfall);
cout << "Average rainfall was: "<<avg<<endl;
cout<<" ";
system("pause");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.