注册 登录
编程论坛 VC++/MFC

用矩形,梯形法,求定积分

bugyangqi 发布于 2011-05-18 12:23, 722 次点击
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define pi 3.14159265358979323846

double f(double x)
{
    return sin (x)+cos (x);

}





double juxing(double (*f)(double),double a,double b)
{
 double i=1.0/1000000;
 double sum=0,x;
 for(x=a;x<=b;)
 {
  sum+=f(x)*i;
  x+=i;
 }
 return sum;
}


double tixing (double(*f)(double),double a,double b)
{
    double i=1.0/1000000;
    double s=0,x;
    for(x=a;x<=b;)
    {
        s+=((f(x)+f(x+i))/2)*i;
        x+=i;
    }
    return s;
}

main ()
{
    char m;
    double a=0, b =pi;
    printf ("输入1(矩形算法) 或 2(梯形算法):\n");
    m=getchar();
    printf("定积分为:\n");

    switch (m)
    {
    case '1':printf ("%lf\n",juxing (f,a,b));break;
    case '2':printf ("%lf\n",tixing (f,a,b));break;

    }



}
0 回复
1