【问题标题】:Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers用 C++ 编写程序,接受 3 个数字并将它们发送到一个函数,然后计算这 3 个数字的平均函数
【发布时间】:2020-06-02 05:59:42
【问题描述】:

用 C++ 编写的程序,接受 3 个数字并将它们发送到一个函数,然后计算这 3 个数字的平均函数。


我知道如何在不使用函数的情况下做到这一点,例如对于任何 n 个数字,我有以下程序:

#include<stdio.h>

int main()
{


    int n, i;
    float sum = 0, x;

    printf("Enter number of elements:  ");
    scanf("%d", &n);
    printf("\n\n\nEnter %d elements\n\n", n);
    for(i = 0; i < n; i++)
    {
        scanf("%f", &x);
        sum += x;
    }
    printf("\n\n\nAverage of the entered numbers is =  %f", (sum/n));

    return 0;
}

或者这个使用数组来做到这一点:

#include <iostream>
using namespace std;

int main()
{
    int n, i;
    float num[100], sum=0.0, average;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 100 || n <= 0)
    {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;

    return 0;
}


但是可以使用函数吗?如果可以,那么如何使用?非常感谢您的帮助。

【问题讨论】:

标签: c++ function average


【解决方案1】:

作为使用基本类型存储值的替代方法,C++ 提供了std::vector 来处理数字存储(具有自动内存管理)而不是普通的旧数组,它还提供了许多工具,例如std::accumulate。使用 C++ 提供的功能可以大大减少您的功能:

double avg (std::vector<int>& i)
{
    /* return sum of elements divided by the number of elements */
    return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}

事实上,一个完整的例子可能只需要十几行额外的代码,例如

#include <iostream>
#include <vector>
#include <numeric>

double avg (std::vector<int>& i)
{
    /* return sum of elements divided by the number of elements */
    return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}

int main (void) {

    int n;                                          /* temporary integer */
    std::vector<int> v {};                          /* vector of int */

    while (std::cin >> n)                           /* while good integer read */
        v.push_back(n);                             /* add to vector */

    std::cout << "\naverage: " << avg(v) << '\n';   /* output result */
}

在上面,输入来自stdin,它将处理您想要输入的整数(或从文件重定向作为输入)。 std::accumulate 只是简单地将向量中存储的整数相加,然后为了完成平均值,您只需除以元素的数量(使用强制转换为 double 以防止整数除法)。

使用/输出示例

$ ./bin/accumulate_vect
10
20
34
done

average: 21.3333

(注意:您可以输入任何非整数(或手动EOF)来结束输入值,"done" 上面只是使用过,但也可以是@987654331 @ 或 "gorilla" -- 任何非整数)

同时使用普通的旧数组很好(因为有很多遗留代码使用它们),但同样很高兴知道编写的新代码可以利用漂亮的容器和数字例程 C++现在提供(并且已经使用了十年左右)。

【讨论】:

    【解决方案2】:

    所以,我为您创建了两个选项,一个使用向量,这真的很舒服,因为您可以使用函数成员找出大小,另一个使用数组

    #include <iostream>
    #include <vector>
    
    float average(std::vector<int> vec)
    {
        float sum = 0;
        for (int i = 0; i < vec.size(); ++i)
        {
            sum += vec[i];
        }
        sum /= vec.size();
        return sum;
    }
    float average(int arr[],const int n)
    {
        float sum = 0;
        for (int i = 0; i < n; ++i)
        {
            sum += arr[i];
        }
        sum /= n;
        return sum;
    }
    int main() {
        std::vector<int> vec = { 1,2,3,4,5,6,99};
        int arr[7] = { 1,2,3,4,5,6,99 };
        std::cout << average(vec) << " " << average(arr, 7);
    }
    

    【讨论】:

      【解决方案3】:

      这是一个示例,旨在让您了解需要做什么。您可以通过以下方式执行此操作:

      // we pass an array "a" that has N elements
      double average(int a[], const int N)
      {
          int sum = 0;
          // we go through each element and we sum them up
          for(int i = 0; i < N; ++i)
          {
              sum+=a[i];
          }
          // we divide the sum by the number of elements
          // but we first have to multiply the number of elements by 1.0
          // in order to prevent integer division from happening
          return sum/(N*1.0);
      }
      
      int main() 
      {
          const int N = 3;
          int a[N];
      
          cin >> a[0] >> a[1] >> a[2];
      
          cout << average(a, N) << endl;
      
          return 0;
      }
      

      【讨论】:

        【解决方案4】:

        如何在不使用函数的情况下做到这一点

        很简单。只需将您的代码放在一个函数中,我们将其称为calculateAveragereturn 的平均值。这个函数应该输入什么?

        • 号码列表 (array of numbers)
        • 总数 (n)

        所以我们先从用户那里得到输入,然后放到数组中,你已经做到了:

            for(int i = 0; i < n; ++i)
            {
                cout << i + 1 << ". Enter number: ";
                cin >> num[i];
            }
        

        现在,让我们创建一个小函数,即calculateAverage()

        int calculateAverage(int numbers[], int total)
        {
            int sum = 0; // always initialize your variables
            for(int i = 0; i < total; ++i)
            {
                sum += numbers[i];
            }
        
            const int average = sum / total; // it is constant and should never change
                                             // so we qualify it as 'const'
            //return this value
            return average
        }
        

        这里有几点需要注意。

        • 将数组传递给函数时,会丢失大小信息,即它包含或可以包含多少元素。这是因为它衰减为一个指针。那么我们如何解决这个问题呢?有几种方法,
          • 在函数中传递大小信息,就像我们传递total
          • 使用std::vector(当您不知道用户将输入多少元素时)。 std::vector 是一个动态数组,它会根据需要增长。如果事先知道元素个数,可以使用std::array

        您的代码存在一些问题:

        using namespace std;

        不要这样做。相反,如果你想要 std 中的某些内容,例如 cout,你可以这样做:

        using std::cout
        using std::cin
        ...
        

        或者你可以每次都写std::cout

            int n, i;
            float num[100], sum=0.0, average;
        

        始终在使用变量之前对其进行初始化。如果您不知道它们应该初始化的值,只需使用{} 进行默认初始化;

            int n{}, i{};
            float num[100]{}, sum=0.0, average{};
        

        在单独的行上声明变量不是强制性的,但是很好的做法。这使您的代码更具可读性。

        【讨论】:

          猜你喜欢
          • 2022-12-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-20
          相关资源
          最近更新 更多