/*设计梯形法求定积分的函数模板,这个方法比之前的那个设计求积分的类要思路简单得多,
而且我个人认为这么想更顺*/
#include<iostream>
#include<cmath>
using namespace std;
class Mysin{
public:
double fun(double x)
{
return (sin(x));
}
};
class F1{
public:
double fun(double x)
{
return (1+x+2*x*x);
}
};
class F2{
public:
double fun(double x)
{
return (1+x+2*x*x+3*x*x*x);
}
};
template<class T>
double JiFenHanShu(T cf,double a,double b,int n)
{
double h,result=0;
h=(b-a)/n;
result += (cf.fun(a)+cf.fun(b))/2;
for(int i=1;i<n;i++)
result += cf.fun(a+i*h);
result *= h;
return result;
}
void main()
{
Mysin f1;
F1 f2;
F2 f3;
double jieguo1;
double jieguo2;
double jieguo3;
jieguo1=JiFenHanShu(f1,0.0,3.0,1000);
cout<<"函数f1的定积分值是:"<<jieguo1<<endl;
jieguo2=JiFenHanShu(f2,0.0,3.0,1000);
cout<<"函数f2的定积分值是:"<<jieguo2<<endl;
}