C语言指针练习之矩形法求定积分

来源:互联网 发布:mybatis显示sql语句 编辑:程序博客网 时间:2024/05/28 11:28
/* *Copyright(c) 2016,烟台大学计算机学院 *All rights reserved. *文件名称:test1.cpp *作    者:刘金石 *完成日期:2016年3月16日 *版本  号:v1.0 *问题描述:写一个用矩形法求定积分的通用函数. *输入描述:输入定积分的上限和下限。 *输出描述:输出sin(x),cos(x),exp(x)的结果。*/#include<stdio.h>#include<math.h>using namespace std;int main(){    float integral(float (*p)(float),float a,float b,int n);    float a1,b1,a2,b2,a3,b3,c,(*p)(float);    float fsin(float);    float fcos(float);    float fexp(float);    int n=20;    scanf("%f%f",&a1,&b1);    scanf("%f%f",&a2,&b2);    scanf("%f%f",&a3,&b3);    p=fsin;    c=integral(p,a1,b1,n);    printf("The integral of sin(x) is :%.2f\n",c);    p=fcos;    c=integral(p,a2,b2,n);    printf("The integral of cos(x) is :%.2f\n",c);    p=fexp;    c=integral(p,a3,b3,n);    printf("The integral of exp(x) is :%.2f\n",c);    return 0;}float integral(float(*p)(float),float a,float b,int n){    int i;    float x,h,s;    h=(b-a)/n;    x=a;    s=0;    for(i=1;i<=n;i++)    {        x=x+h;        s=s+(*p)(x)*h;    }    return s;}float fsin(float x){     return sin(x);}float fcos(float x){     return cos(x);}float fexp(float x){     return exp(x);}

运行结果:


0 0
原创粉丝点击