我必须编写一个程序来询问用户的年数,然后询问用户在这些年中每个月的降雨量(毫米)。我必须计算月数、总降雨量、每月平均降雨量,计算所有月份的最大降雨量,并输出月份名称(将月份数字转换为名称)和降雨量最大的年份。到目前为止,我已经写了这段代码,但是我不知道如何准确地输出确切的月份名称和降雨量最大的年份,即使我已经计算了最高降雨量。
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;
发布于 2011-10-12 06:54:04
不如这样吧:
if (rain > largest_rain){
largest_rain = rain;
largest_month = months;
largest_year = years;
}
发布于 2011-10-12 07:02:11
要将月份数映射到名称,我会将它们放入字符串数组中。
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];
https://stackoverflow.com/questions/7733468
复制相似问题