首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++嵌套循环

C++嵌套循环
EN

Stack Overflow用户
提问于 2011-10-12 06:51:05
回答 2查看 2.2K关注 0票数 1

我必须编写一个程序来询问用户的年数,然后询问用户在这些年中每个月的降雨量(毫米)。我必须计算月数、总降雨量、每月平均降雨量,计算所有月份的最大降雨量,并输出月份名称(将月份数字转换为名称)和降雨量最大的年份。到目前为止,我已经写了这段代码,但是我不知道如何准确地输出确切的月份名称和降雨量最大的年份,即使我已经计算了最高降雨量。

代码语言:javascript
运行
复制
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;
EN

回答 2

Stack Overflow用户

发布于 2011-10-12 06:54:04

不如这样吧:

代码语言:javascript
运行
复制
   if (rain > largest_rain){        
        largest_rain = rain;
        largest_month = months;
        largest_year = years;
    }
票数 3
EN

Stack Overflow用户

发布于 2011-10-12 07:02:11

要将月份数映射到名称,我会将它们放入字符串数组中。

代码语言:javascript
运行
复制
string[] months = {"January","February","March"...};

然后取您的月份数字(如果是1索引,则减去1),并将该索引打印到数组中。

所以综合起来看起来是这样的:

代码语言:javascript
运行
复制
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];
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7733468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档