2011-10-11 201 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