声明原型时如何在主代码块中调用函数

How to call a function in the main block of code when a prototype is declared

本文关键字:代码 调用 函数 原型 声明      更新时间:2023-10-16

我正在为类编写代码,该代码涉及与梯形规则和离散数据点进行数值积分。部分指令说要用原型调用函数:

double trapInt(const double xvals[], const double yvals[], int nElements);

我已经在代码的"int main"部分之前声明了原型,但我不完全理解调用函数的确切步骤。

注意:代码涉及使用一维数组。如果看到这会有所帮助,我也有作业的 PDF。

#include <iostream>
#include <ifstream>

using namespace std;
double trapInt(const double xvals[], const double yvals[], int nElements);

int main()
{
const int MAX_SIZE = 101;
double xData[MAX_SIZE];
double yData[MAX_SIZE];
ifstream infile("trapezoidData.txt");
if(infile.fail())
  {
    for(int a=0; a<MAX_SIZE; ++a)
    {
      infile >> xData[a] >> yData[a];
      cout << xData[a] << 't' << yData[a] << endl;
  }
}
else
{
  cout << "Could not open infile." << endl;
}
cout.setf(ios::fixed);
cout.precision(3);
return 0;
}

调用函数非常简单。您要做的就是给出函数的名称,并放置参数,类似于如何声明原型:

main () {
    // implementation...
    trapInt(xvals, yvals, nElements);
    // more implementation...
}

但请记住,仅将此行(或类似的行(添加到您的 main 函数中将无法在没有实现的情况下编译:

double trapInt(const double xvals[], const double yvals[], int nElements) {
    // implementation of the function...
}

编辑:我原本想把函数的调用留给你一个练习,但如果你真的在黑暗中,我会给你举一个例子:

<块引用类>

trapInt(xData, yData, MAX_SIZE(;

只需将该行添加到您的main()中即可。