/*设计梯形法求积分的类模板,梯形法求积分的函数被定义为成员函数,可以求任意函数的定积分,用积分类的模板参数T引入被积函数*/
#include<iostream>
#include<cmath>
#include<iomanip>
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>
class JiFenLei{
private:
double a,b,h,result;
int n;
T cf;
public:
JiFenLei(double x=0,double y=0,int m=100)
{
a=x;
b=y;
n=m;
jifenhanshu();//初始化后就地再类的内部进行积分,
//但是感觉这样一定要注意构造函数的调用情况,千万不可随意调用构造函数
}
void print()
{
cout<<"定积分的值为:"<<result<<endl;
}
void xiugaitiaojian(double x=0,double y=0,int m=100)
{
a=x;
b=y;
n=m;
}
void jifenhanshu();
};
template<class T>
void JiFenLei<T>::jifenhanshu()
{
h=(b-a)/n;
int i;
result=(cf.fun(a)+cf.fun(b))/2;
for(i=1;i<n;i++)
result += cf.fun(a+i*h);
result = result*h;
}
void main()
{
JiFenLei<Mysin>J1(0.0,3.0,100);
J1.print();
JiFenLei<F1>J2(0.0,3.0,100);
J2.print();
}