利用多态编写求积分程序
时间: 2023-12-09 12:06:05 浏览: 25
以下是一个简单的利用多态编写的求积分程序,包含了不同类型的积分方法:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class IntegralMethod{
public:
virtual double integrate(double a, double b, int n) = 0;
};
class TrapezoidMethod : public IntegralMethod{
public:
double integrate(double a, double b, int n){
double h = (b - a) / n;
double res = 0.0;
for(int i=1; i<n; i++){
double x = a + i*h;
res += f(x);
}
res += (f(a) + f(b)) / 2.0;
res *= h;
return res;
}
private:
virtual double f(double x){
return x*x;
}
};
class SimpsonMethod : public IntegralMethod{
public:
double integrate(double a, double b, int n){
double h = (b - a) / n;
double res = f(a) + f(b);
for(int i=1; i<n; i++){
double x = a + i*h;
res += (i % 2 == 0) ? 2*f(x) : 4*f(x);
}
res *= h/3.0;
return res;
}
private:
virtual double f(double x){
return sin(x);
}
};
int main(){
IntegralMethod* method = new TrapezoidMethod();
double integral = method->integrate(0.0, 1.0, 1000);
cout << "Trapezoid method: " << integral << endl;
delete method;
method = new SimpsonMethod();
integral = method->integrate(0.0, 1.0, 1000);
cout << "Simpson method: " << integral << endl;
delete method;
return 0;
}
```
上述代码中,定义了一个抽象的`IntegralMethod`类,它包含了一个纯虚函数`integrate()`,用于计算积分。然后,分别定义了两个具体的积分方法类:`TrapezoidMethod`和`SimpsonMethod`。这两个类均继承于`IntegralMethod`类,并实现了`integrate()`函数。
在`main()`函数中,先定义了一个指向`TrapezoidMethod`的指针`method`,然后调用`integrate()`函数计算积分,并输出结果。接着,重新定义指针`method`指向`SimpsonMethod`,并再次计算积分并输出结果。最后,释放指针`method`所占用的内存。