簡體   English   中英

C ++嵌套循環

[英]C++ nested loops

我必須編寫一個程序,詢問用戶多年,然后詢問用戶這些年中每個月的降雨量(mm)。 我必須計算總月數,總降雨量,每月平均降雨量,計算所有月份的最大降雨量,並輸出月份名稱(將月份數字轉換為名稱)和具有最大降雨量的年份。 到目前為止我已經編寫了這段代碼,但是我無法弄清楚如何准確輸出確切的月份名稱和降雨量最多的年份,即使我已計算出最高的降雨量值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM