You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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大返回1b大返回-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';
}