【学习笔记】【函数指针做参数案例】C语言习题:写一个用矩形法求定积分的通用函数

题目要求:

 

用矩阵法求定积分算法较为简单,其中传递不同函数用到的方法是函数指针。

在C语言中,函数名就是函数的首地址,所以将函数作为函数参数的思路是将函数地址传入,形参是一个指针类型的变量,形参的基类型为函数原型。
参数原型为:

ElemType(*FunctionName)(ElemType, ElemType,······)

因此此题中,声明定积分近似值计算通用函数为:

double integrate(double (*f)(double),double down,double up);

其中,(*f)(double)为函数指针,down为下标,up为上标。

于是有代码如下:

#include<stdio.h>
#include<math.h>
#define dx 0.001 //dx越小,精度越大

double integrate(double (*f)(double),double down,double up){
    double sum=0,step;
    for(step=down;step<up;step+=dx)
        sum+=(*f)(step)*dx;
    return sum;
}

int main(){
    printf("%.4f\n",integrate(sin,0,1));
    printf("%.4f\n",integrate(cos,0,1));
    printf("%.4f\n",integrate(exp,0,1));
    system("pause");
}

输出结果为:

0.4593
0.8417
1.7174

用 Mathematica 12 计算三个定积分得到的值是 0.459698,0.841471,1.71828,精度还行。

——————完——————

猜你喜欢

转载自www.cnblogs.com/adesoe/p/12815494.html