【问题标题】:c++ arrays using for loops to output rainfall statisticsc++数组使用for循环输出降雨统计
【发布时间】:2018-11-21 12:00:32
【问题描述】:

编写一个程序,读取 12 个月中每个月的降雨量并输出该月和该月的降雨量。然后它应该输出降雨量最多的月份、降雨量最少的月份、全年降雨量和月平均降雨量。所有降雨量均应输出小数点后两位有效数字。

该程序应包含两个并行数组:包含月份名称的字符串类型月份,以及包含相应月份降雨量(以英寸为单位)的 double 类型的降雨量。

提示:请查看 CS1336_Lect7c_Arrays_Compare_Parallel.pptx 的幻灯片 8 至 10 以获取示例。 程序应使用 for 循环读取每个月的降雨量。

程序应输出右对齐的月份,字段宽度为 10,相应的降雨量右对齐,字段宽度为 6。

程序应计算并显示当年的总降雨量和月平均降雨量。

程序应计算最高和最低金额并显示金额和相应的月​​份名称。

提示 1:查看 CS1336_Lect7c_Arrays_Compare_Parallel.pptx 的幻灯片 3 和 4 中的代码以找到最低和最高的代码。

提示 2:此外,您必须跟踪找到最高和最低金额的索引。输出索引对应的月份名称。例如,如果字体雨量[3]是最低雨量,您将打印字体月份[3]作为对应的月份。

验证:月降雨量数据不接受负数。 当输入如图 1 所示时,您的程序应产生如图 2 所示的输出。

图1:(输入)

3.2 .55 -1.2 -.9 2.2 .56 .24 .95 2.00 .35 5.9 1.1 2.8 .3

图2:(输出)

   January  3.20
  February  0.55
     March  2.20
     April  0.56
       May  0.24
      June  0.95
      July  2.00
    August  0.35
 September  5.90
   October  1.10
  November  2.80
  December  0.30

The most rainfall was 5.90 inches in September.
The least rainfall was 0.24 inches in May.
The total amount of rainfall for the year is 20.15 inches.
The average monthly rainfall for the year is 1.68 inches.

这是我的代码。

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
   const int SIZE = 12;
   string months[] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
   double rainfall [SIZE];
   double highest;
   double lowest;
   double total, average;

   cin >> rainfall[SIZE];

   for (int i = 0; i < SIZE; i++)
   {
      cout << right << setw(10) << months[SIZE] << right <<setw(6) << rainfall[i] << endl;
   }

   for ( int i = 0; i < SIZE; i++)
   {
      if (rainfall[i] > highest)
      {
         highest = rainfall[i];
      }
   }
   for (int i = 0; i < SIZE; i++)
   {
      if (rainfall[i] < lowest)
      {
         lowest = rainfall[i];
      }

   }
   for(int i = 0; i < SIZE; i++)
      {

        total = rainfall[0] + rainfall[1] + rainfall[2] + rainfall[3] + rainfall[4];
        cout << "The total amount of rainfall for the year is " << total << " inches." << endl;
      }
      for(int i = 0; i << SIZE; i++)
      {
         average = total / SIZE;
         cout << "The average monthly rainfall for the year is " << average << " inches." << endl;
      }

   return 0;
}

【问题讨论】:

  • 不确定我在运行时做错了什么,我没有得到输出
  • 这条线应该做什么cin &gt;&gt; rainfall[SIZE];
  • 你可以而且必须使用一个循环,而不是五个。
  • 它应该在显示的输入中读取
  • @LouisCastillo 猜你想用降雨次数填充数组rainfall

标签: c++


【解决方案1】:

我已经修复了你的代码,并在我认为你离线的地方添加了评论。请根据您的输入进行尝试,最重要的是了解代码中所做的更改以及为什么这会解决您的代码中的问题。这样,您不仅可以应对/粘贴代码,还可以在此过程中学习。编码愉快!

#include "stdafx.h"    
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
    const int SIZE = 12;
    string months[]{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
    double rainfall[SIZE];
    double highest = 0.0;
    double lowest = 0.0;
    double total = 0.0, average = 0.0;

    double input;
    for (int i = 0; i < SIZE; ) //Dont increment i here since we want to ignore negative numbers.
    {
        cin >> input;
        cin.ignore(1000, '\n');
        if (input > 0.0)
        {
            rainfall[i] = input;

            //for the first element assign lowest and highest to same value.
            if (i == 0)
            {
                highest = input;
                lowest = input;
            }

            if (input > highest) highest = input;
            if (input < lowest) lowest = input;
            total += rainfall[i]; //You need to keep adding all the months rainfall in total. ? why did you add only four and that too in loop?
            i++; //if the number is non negative increment i.
        }
    }


    for (int i = 0; i < SIZE; i++)
    {
        cout << right << setw(10) << months[i] << right << setw(6) << rainfall[i] << endl;
    }

    average = total / SIZE;

    cout << "The total amount of rainfall for the year is " << total << " inches." << endl;
    cout << "The highest amount of rainfall for the year is " << highest << " inches." << endl;
    cout << "The lowest amount of rainfall for the year is " << lowest << " inches." << endl;
    cout << "The average monthly rainfall for the year is " << average << " inches." << endl;

    return 0;
}

【讨论】:

    【解决方案2】:

    您的说明相当具体和充分。一次拿一个。对于初学者,您需要验证您已将 12 月份的降雨数据读取到 double 的数组中。要声明数组并验证读取的降雨量数量,您将需要一个常数。所以:

    #include <iostream>
    #include <iomanip>
    #include <string>
    
    using namespace std;
    
    #define MONTHS 12   /* if you need a constant, #define one (or more) */
    

    您可以选择在哪里声明您的 string 数组,其中包含每个 month 的名称。您可以将数组声明为main() 的本地数组,也可以将名称声明为全局数组(可能更可取)。您不会更改每个月的名称,因此您应该将数组限定为 const,例如

    int main (void) {
    
        double rainfall[MONTHS] = {0},  /* declare/initialize variables */
            sum = 0, min = 10000, max = 0, avg = 0;
        const string month[] =  { "January", "February", "March", "April",
                            "May", "June", "July", "August",
                            "September", "October", "November", "December" };
        int mo = 0, maxmo = 0, minmo = 0;
    

    当您在循环中读取多个输入时,您希望根据有效输入控制循环并确保没有发生流错误 (eofbit, failbit, badbit)在使用数据之前 .在您的情况下,只需一个读取循环即可读取信息、计算totalaverage 使用的sum 以及确定maxmin 以及月份每个发生的位置(maxmominmo)。 (注意: min 已初始化得足够大,以便它可以处理确定实际最小值。初始化为 0 将不起作用)

        while ((cin >> rainfall[mo])) {     /* while good input */
            if (rainfall[mo] > 0) {         /* validate positive rainfall */
                sum += rainfall[mo];        /* increment sum by rainfall */
                if (rainfall[mo] < min)     /* set min and minmo */
                    min = rainfall[mo], minmo = mo;
                if (rainfall[mo] > max)     /* set max and maxmo */
                    max = rainfall[mo], maxmo = mo;
                mo++;
            }
        }
    

    现在您的读取循环已完成,您可能想要验证您实际上拥有 12 个月的降雨数据,然后计算平均值,例如:

        if (mo != MONTHS)   /* valdate 12 months of data read */
            cerr << "warning: only '" << mo << "' months data available.\n";
    
        avg = sum / (double)mo;
    

    剩下的就是格式化输出。默认对齐方式为right,因此无需包含该格式修饰符,但您需要使用std::fixedstd::setprecision() 来格式化您的浮点数字输出,并保留两位小数。除非您在后续输出中对它们进行更改,否则您只需要设置一次。您可以简单地设置:

        cout << fixed << setprecision(2);   /* set fixed and precision(2) */
    

    浮点输出现在将以两位小数输出。剩下的就是输出所需的信息,例如

        for (int i = 0; i < mo; i++)        /* output monthly data */
            cout << setw(10) << month[i] << setw(6) << rainfall[i] << '\n';
    
        /* output statistics */
        cout << "\nThe most rainfall was " << max << " inches in "
                << month[maxmo] << ".\n";
        cout << "The least rainfall was " << min << " inches in "
                << month[minmo] << ".\n";
        cout << "The total amount of rainfall for the year is "
                << sum << " inches.\n";
        cout << "The average monthly rainfall for the year is "
                << avg << " inches.\n";
    

    注意:上面实际上不需要多次调用cout,你可以简单地使用一个cout并将所有信息串在一起)

    总而言之,您可以执行以下操作:

    #include <iostream>
    #include <iomanip>
    #include <string>
    
    using namespace std;
    
    #define MONTHS 12   /* if you need a constant, #define one (or more) */
    
    int main (void) {
    
        double rainfall[MONTHS] = {0},  /* declare/initialize variables */
            sum = 0, min = 10000, max = 0, avg = 0;
        const string month[] =  { "January", "February", "March", "April",
                            "May", "June", "July", "August",
                            "September", "October", "November", "December" };
        int mo = 0, maxmo = 0, minmo = 0;
    
        while ((cin >> rainfall[mo])) {     /* while good input */
            if (rainfall[mo] > 0) {         /* validate positive rainfall */
                sum += rainfall[mo];        /* increment sum by rainfall */
                if (rainfall[mo] < min)     /* set min and minmo */
                    min = rainfall[mo], minmo = mo;
                if (rainfall[mo] > max)     /* set max and maxmo */
                    max = rainfall[mo], maxmo = mo;
                mo++;
            }
        }
    
        if (mo != MONTHS)   /* valdate 12 months of data read */
            cerr << "warning: only '" << mo << "' months data available.\n";
    
        avg = sum / (double)mo;
    
        cout << fixed << setprecision(2);   /* set fixed and precision(2) */
        for (int i = 0; i < mo; i++)        /* output monthly data */
            cout << setw(10) << month[i] << setw(6) << rainfall[i] << '\n';
    
        /* output statistics */
        cout << "\nThe most rainfall was " << max << " inches in "
                << month[maxmo] << ".\n";
        cout << "The least rainfall was " << min << " inches in "
                << month[minmo] << ".\n";
        cout << "The total amount of rainfall for the year is "
                << sum << " inches.\n";
        cout << "The average monthly rainfall for the year is "
                << avg << " inches.\n";
    }
    

    使用/输出示例

    $ echo "3.2 .55 -1.2 -.9 2.2 .56 .24 .95 2.00 .35 5.9 1.1 2.8 .3" | \
    ./bin/rainfall
       January  3.20
      February  0.55
         March  2.20
         April  0.56
           May  0.24
          June  0.95
          July  2.00
        August  0.35
     September  5.90
       October  1.10
      November  2.80
      December  0.30
    
    The most rainfall was 5.90 inches in September.
    The least rainfall was 0.24 inches in May.
    The total amount of rainfall for the year is 20.15 inches.
    The average monthly rainfall for the year is 1.68 inches.
    

    检查一下,如果您还有其他问题,请告诉我。

    【讨论】:

      【解决方案3】:
      1. 变量SIZE 没有任何意义,因为你知道那一年总是有12 个月。它只会浪费内存。如果您想使用某种变量,请使用#define SIZE 12。将其放在#include 部分下方的顶部。
      2. 使用只能对所有任务使用一个循环。
      3. 最后两个循环也没有意义。如果要计算总降雨量,请将total += rainfall[i]; 放入循环中。
      4. cin &gt;&gt; rainfall[SIZE]; 也毫无意义,也不正确。为什么?使用该行,您实际上会将值放入 rainfall[12];,但 rainfall 的最后一个索引是 11 而不是 12。 要使用值填充 rainfall,请将 cin &gt;&gt; ranfall[i]; 放入循环中。您必须使用两个不同的循环来填充 rainfall 并计算所有其他内容。

      【讨论】:

      • 强烈反对第 1 点。强烈反对第 1 点的解决方案。一个体面的编译器会在需要的地方看到const int SIZE = 12;and sub in 12。没有内存成本,也没有#define SIZE 12 带来的宏替换问题。如果你想改进const int SIZE = 12;,请使用constexpr int SIZE = 12;
      • 不知道他用的是什么编译器。
      猜你喜欢
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多