2011-10-11 167 views
1

我必須編寫一個程序,詢問用戶的年數,然後詢問用戶在這些年中每月的降雨量。我必須計算總月數,降雨總英寸數,每月平均降雨量,計算所有月份的最大降雨量,並輸出月份名稱(將月份數字轉換爲名稱)和年降雨量最大的年份。我已經寫了這段代碼,但我無法弄清楚如何準確地輸出確切的月份名稱和降雨量最高的年份,儘管我已經計算出了最高降雨量值。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; 

回答

3

如何像:

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

是的,但是我怎麼會得到實際的月份名稱顯示出來?像1月,2月等。 – user566094

+0

@ user566094您需要一個查找表。你可以使用'vector ',因爲你的索引是整數(並且你偏移了1)。 –

+0

枚舉適合這裏: [鏈接](http://msdn.microsoft.com/en-us/library/2dzy4k6e(v = vs.80).aspx)。 – deyur

1

到幾個月的映射號碼名字,我會放在一個字符串數組。

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

它告訴我'''找不到操作符找到右手操作數類型'std :: string'(或者沒有可接受的轉換 – user566094

+0

@ user566094:這意味着你的源文件丟失了#include '或'#include '。 – ildjarn

+0

嘿,你知道我如何執行用戶輸入驗證,它實現了用戶無法輸入負值的雨? – user566094