函数和数组

Functions and arrays

本文关键字:数组 函数      更新时间:2023-10-16

问题是

设计等级处理程序以使用函数和数组。让用户输入成绩数(将最大值设置为 50)。将成绩存储在数组中。为每个计算创建一个单独的函数(总共 3 个函数):1) 平均成绩,2) 最高成绩,3) 高于平均水平的成绩数。 显示所有结果。

我想我得到了主要部分,但我在如何编写函数方面遇到了问题,由于某种原因,函数输出了一个函数,而且我在编写 max 函数或如何启动它时遇到了麻烦。

#include <iostream>
using namespace std;
double average(double x[], int n);
double maximum(double x[], int n);
int nAboveAvg(double x[], int n);
int main()
{
    double grades[50];
    int ngrades;
    cout<<"How many grades? (max = 50)";
    cin>>ngrades;
//create for loop to get grades from user
    for(int i = 0; i<ngrades; i++)
    {
         cout<<"Enter grade ";
         cin>> grades[i];
    }
      //call the functions
   double avg = average(grades, ngrades);
   double max = maximum(grades, ngrades);
   int nAbove = nAboveAvg(grades, ngrades);
   //display results
   cout<<"Average = "<<avg<<endl;
   cout<<"# above average = "<<nAbove<<endl;

}
double average(double x[], int npts) //define the functon to recieve the array
{
    double sum = 0;
    for(int k = 0; k<npts; k++)
    {
       sum = sum +x[k];
    }
    return sum / npts;
}
double maximum(double x[], int npts)
{
   double max = 0;
   for(int i = 0; i<npts; i++)
   {
      if(max == npts)
      {
          return max;
      }
      if(max < npts)
      {
          return npts;
      }
   }
}
int nAboveAvg(double x[], int npts)
{
    int nAboveAvg = 0;
    for(int i = 0; i<npts;i++)
    {
        if(x[i] > npts)
        {
            nAboveAvg++;
        }
    }
    return nAboveAvg;
}

打印不正确

//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);

请注意,您定义了名为 avgnAbove 的变量。

//display results
cout<<"Average = "<<average<<endl;
cout<<"# above average = "<<nAboveAvg<<endl;

但是,当您尝试打印结果时,您可以使用averagenAboveAvg(函数)。

此处的正确版本是:

cout << "Average = " << avg << endl;
cout << "# above average = " << nAbove << endl;

编译器警告

当我尝试编译它时,编译器会发出许多警告。

main.cpp: In function 'int main()':
main.cpp:29:24: warning: the address of 'double average(double*, int)' will always evaluate as 'true' [-Waddress]
    cout<<"Average = "<<average<<endl;

main.cpp:24:11: warning: unused variable 'avg' [-Wunused-variable]
    double avg = average(grades, ngrades);

最好不要忽视这些警告。


计数高于平均水平

        if(x[i] > npts)
        {
            nAboveAvg++;
        }

位置 i 处的值输入值的数量进行比较。但是,您应该将位置 i 的值所有值的平均值进行比较。因此

int nAboveAvg(double x[], int npts)
{
    int count = 0;
    double avg = average(x, npts);
    for (int i(0); i < npts; ++i) {
        if (x[i] > avg) {
            ++count;
        }
    }
    return count;
}

重构

您现在可能会注意到,在我们的程序中,我们最终会计算两次平均值。我们可以通过使我们的函数更通用来解决这个问题 - 让我们计算作为参数传递的任意目标以上的值的数量,而不是计算高于平均值的值数量。

int count_above(double x[], int npts, double target)
{
    int count = 0;
    for (int i(0); i < npts; ++i) {
        if (x[i] > target) {
            ++count;
        }
    }
    return count;
}

现在我们可以写了

//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = count_above(grades, ngrades, avg);

最大值

让我们考虑一下算法,并从最简单的情况开始 - 数组中只有一个值。在此方案中,第一个值也是最大值。

double max = x[0];

知道了这一点,让我们考虑当输入数组中有 2 个值时如何找到最大值。我们已经知道第二个值之前所有值的最大值。因此

if (x[1] > max) {
    max = x[1];
}

下一步,输入具有 3 个值的数组。同样,我们已经知道第三个值之前所有值的最大值。因此

if (x[2] > max) {
    max = x[2];
}

我们可以看到一个模式在这里重复,我们可以将其包装成一个循环。

double maximum(double x[], int npts)
{
    if (npts <= 0) {
        exit(-1); // Error...
    }
    double max = x[0];
    for (int i(1); i < npts; ++i) {
        if (x[i] > max) {
            max = x[i];
        }
    }
    return max;
}

验证输入

您没有对传递给函数的输入进行任何验证,但需要考虑一些明显的情况。

  • 在您的所有函数中,当npts为负时会发生什么?
  • 0 元素的平均值是多少?
  • 0 元素的最大值是多少?

处理这些情况的一个非常简单的方法是返回一些特殊值作为结果。然后,每次调用函数时都必须检查此值的结果。在许多情况下,可能很难为此选择适当的值。

初学者可以接受的另一种可能性是简单地将一些错误消息打印到控制台,然后退出程序。例如

if (npts <= 0) {
    cerr << "Too few values in input array." << endl;
    exit(-1); // Error...
}

正确的C++方法是抛出异常,例如 std::invalid_argument。例如

#include <stdexcept>
// ....
if (npts <= 0) {
    throw std::invalid_argument("Too few values in input array.);
}

"average"函数看起来不错。 在main的最后2行中,我认为您要输出avg而不是average(因为average是函数的名称,而不是保存计算值的变量的名称)。 同样,输出 nAbove 而不是 nAboveAvg。

最大函数看起来像一个空的实现。 我认为这不会编译,因为它需要(至少)返回一个双精度值。

在nAboveAvg函数中,"x[i]> npts"似乎是错误的测试。 我想你想将 x[i] 与 avg 进行比较(你会想将 avg 作为参数传递到这个函数中。