|
|
@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
#include <string>
|
|
|
|
|
|
|
|
using std::cout, std::string, std::endl;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Integrate
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
protected:
|
|
|
|
|
|
|
|
double a, b;
|
|
|
|
|
|
|
|
int n;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public:
|
|
|
|
|
|
|
|
virtual double fun(double x) = 0;
|
|
|
|
|
|
|
|
Integrate(double _a, double _b, int _n = 10000) : a{_a}, b{_b}, n{_n} {}
|
|
|
|
|
|
|
|
double integrate()
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
double result{(fun(a) + fun(b)) / 2};
|
|
|
|
|
|
|
|
double h{(b - a) / n};
|
|
|
|
|
|
|
|
for (int i{1}; i < n; i++)
|
|
|
|
|
|
|
|
result += fun(a + i * h);
|
|
|
|
|
|
|
|
result *= h;
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class F1 : public Integrate
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
public:
|
|
|
|
|
|
|
|
using Integrate::Integrate;
|
|
|
|
|
|
|
|
double fun(double x) override
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
return x;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class F2 : public Integrate
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
public:
|
|
|
|
|
|
|
|
using Integrate::Integrate;
|
|
|
|
|
|
|
|
double fun(double x) override
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
return x * x;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class F3 : public Integrate
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
public:
|
|
|
|
|
|
|
|
using Integrate::Integrate;
|
|
|
|
|
|
|
|
double fun(double x) override
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
return x * x * x;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
int compare(Integrate &a, Integrate &b)
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
// 比较两个积分对象值的结果,a大返回1,b大返回-1,相同返回0
|
|
|
|
|
|
|
|
if (a.integrate() > b.integrate())
|
|
|
|
|
|
|
|
return 1;
|
|
|
|
|
|
|
|
if (a.integrate() < b.integrate())
|
|
|
|
|
|
|
|
return -1;
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
int main()
|
|
|
|
|
|
|
|
{
|
|
|
|
|
|
|
|
F1 f1{0, 1};
|
|
|
|
|
|
|
|
F2 f2{0, 1};
|
|
|
|
|
|
|
|
F3 f3{0, 1};
|
|
|
|
|
|
|
|
cout << f1.integrate() << ' ' << f2.integrate() << ' ' << f3.integrate() << '\n';
|
|
|
|
|
|
|
|
// 设计通用接口compare,积分类的任意派生对象可进行比较
|
|
|
|
|
|
|
|
cout << compare(f1, f2) << '\n';
|
|
|
|
|
|
|
|
cout << compare(f1, f3) << '\n';
|
|
|
|
|
|
|
|
cout << compare(f2, f3) << '\n';
|
|
|
|
|
|
|
|
}
|