开发者

C++ nested loops

开发者 https://www.devze.com 2023-04-12 03:53 出处:网络
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 inch

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; y开发者_StackOverflow社区ears <= 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];
0

精彩评论

暂无评论...
验证码 换一张
取 消