【发布时间】:2011-10-11 22:51:04
【问题描述】:
我必须编写一个程序,询问用户年数,然后向用户询问这些年中每个月的降雨量(以毫米为单位)。我必须计算总月数、总降雨量、每月平均降雨量、计算所有月份的最大降雨量,并输出月份名称(将月份数字转换为名称)和降雨量最大的年份。到目前为止我已经编写了这段代码,但是我无法弄清楚如何准确输出确切的月份名称和降雨量最高的年份,即使我已经计算了最高降雨量值。
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;
【问题讨论】: