⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exp11_3.cpp

📁 高等教育出版社出版的C++程序设计同步实验范例 希望对用这本教材得同学有点帮助
💻 CPP
字号:
/*设计辛普生法求函数的定积分的类模板,可求任一函数的定积分。在梯形法中是用直线
来代替曲边梯形的曲边,在辛普生法中是用抛物线来代替,区间必须为偶数n个相等区间。 
以模板参数T来引入被积函数类,由该参数调用欲求定积分的函数。
范例:
*/
#include <iostream.h>
#include <iomanip.h>
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);}
};
class F3 {
public:
	double fun(double x){return (1+x+2*x*x+3*x*x*x+4*x*x*x*x);}
};
template<typename T>class Integer{
	double a,b,step,result;
	int n;//分区数量
	T cf;//被积函数
public:
	Integer(double aa=0, double bb=0, int nn=100){
		a=aa;	b=bb;	n=nn;
		integerate();
	}
	void putlimits(double aa=0, double bb=0, int nn=100){//修改上下限和分区数
		a=aa;	b=bb;	n=nn;
	}
	void integerate();
	void print(){cout<<"定积分值为:"<<result<<endl;}
};
template<typename T>void Integer<T>::integerate(){//辛普生法求函数的定积分
	int i;
	step=(b-a)/n;
	result=cf.fun(a)+cf.fun(b);
	for(i=1;i<n;i+=2) result+=4*cf.fun(a+i*step);
	for(i=2;i<n;i+=2) result+=2*cf.fun(a+i*step);
result*=step/3;
}

void main(){
	Integer<F1> integer1(0.0,3.0,1000);
	integer1.print();
	Integer<F2> integer2(0.0,3.0,1000);
	integer2.print();
	Integer<F3> integer3(0.0,3.0,1000);
	integer3.print();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -