c++嵌套循环

C++ nested loops

本文关键字:嵌套循环 c++      更新时间:2023-10-16

我必须编写一个程序,向用户询问年数,然后向用户询问这些年中每个月以毫米为单位的降雨量。我必须计算总月份数、总降雨量英寸数、每月平均降雨量、计算所有月份的最大降雨量,并输出降雨量最大的月份名称(将月份数字转换为名称)和年份。到目前为止,我已经编写了这段代码,但是我不知道如何准确地输出确切的月份名称和降雨量最高的年份,即使我已经计算出降雨量最高的值。

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;

不如这样写:

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

要将月数映射到名称,我将它们放在字符串数组中。

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

然后取月数(如果是1索引则减去1)并将该索引打印到数组中。

所以它们合起来是这样的

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];