【问题标题】:C++ nested loopsC++ 嵌套循环
【发布时间】: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;

【问题讨论】:

    标签: c++ loops nested


    【解决方案1】:

    怎么样:

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

    【讨论】:

    • 是的,但如何才能显示实际月份名称?比如一月、二月等。
    • @user566094 您需要一个查找表。您可以使用 vector&lt;string&gt;,因为您的索引是整数(并且您偏移 1)。
    • 这里适合使用枚举:link.
    • 嘿,你知道我如何执行用户输入验证,实现用户不能为雨输入负值吗?
    【解决方案2】:

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

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

    【讨论】:

    • 它告诉我'
    • @user566094 :这意味着您的源文件缺少#include &lt;string&gt; 或#include &lt;iostream&gt;。
    • 嘿,你知道我如何执行用户输入验证,实现用户不能为雨输入负值吗?
    猜你喜欢
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2014-09-14
    • 2017-07-08
    • 2015-05-29
    相关资源
    最近更新 更多