我必須編寫一個程序,詢問用戶的年數,然後詢問用戶在這些年中每月的降雨量。我必須計算總月數,降雨總英寸數,每月平均降雨量,計算所有月份的最大降雨量,並輸出月份名稱(將月份數字轉換爲名稱)和年降雨量最大的年份。我已經寫了這段代碼,但我無法弄清楚如何準確地輸出確切的月份名稱和降雨量最高的年份,儘管我已經計算出了最高降雨量值。C++嵌套循環
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;
是的,但是我怎麼會得到實際的月份名稱顯示出來?像1月,2月等。 – user566094
@ user566094您需要一個查找表。你可以使用'vector',因爲你的索引是整數(並且你偏移了1)。 –
枚舉適合這裏: [鏈接](http://msdn.microsoft.com/en-us/library/2dzy4k6e(v = vs.80).aspx)。 – deyur