简体   繁体   中英

C++ nested loops

I have to write a program that asks the user for number of years, then ask the user for the rainfall in mm for each month during those years. I have to calculate the total number of months, total inches of rainfall, average rainfall per month, calculate the maximum rainfall for all months, and output the month name (translate the month number to the name) and year that had the maximum rainfall. I have written this code so far, however I cannot figure out how to exactly output the exact month name and the year which had the highest rainfall, even though I have calculated the highest rainfall value.

const int numMonths = 12;
int numYears, months, largest = 0;
double sum = 0;


cout << "Please enter the number of years: ";
cin >> numYears;
cin.ignore();

for (int years = 1; years <= numYears; years ++)
{
    for (int months = 1; months <= numMonths; months ++)
    {
    double rain;
    cout << "Please enter the rainfall in mm for year " << years << ", month " << months << "\n";
    cin >> rain;
    sum += rain;
    if (rain > largest){

        largest = rain;

    }
    cin.ignore();
    }   
}

int totalMonth = numYears*numMonths;
double avgRain = sum / totalMonth;
cout << "Total number of months: " << totalMonth << "\n";
cout << "Total inches of rainfall for the entire period: "<< sum << "\n";
cout << "Average rainfall per month for the entire period: " << avgRain << "\n"; 
cout << "Highest rainfall was " << largest << ;






cin.get();
return 0;

How about something like:

   if (rain > largest_rain){        
        largest_rain = rain;
        largest_month = months;
        largest_year = years;
    }

To map the numbers of months to names I would put them in a string array.

string[] months = {"January","February","March"...};

Then take your month number (subtract 1 if you are 1 indexing) and print out that index into the array.

So all together it looks like this:

string [] month = {"January","February", "March"/*Fill in the rest of the months*/};
int largestMonthIndex = largest_month-1;  
cout << "Month that the largest rain fall occurred in: " <<month[largetMonthIndex];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM