From 53ef764c7f61ffce72ca4d1638600d2e34b22ae0 Mon Sep 17 00:00:00 2001 From: p68710245 Date: Wed, 24 Apr 2024 22:36:52 +0800 Subject: [PATCH] Add Integrate.cpp --- Integrate.cpp | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Integrate.cpp diff --git a/Integrate.cpp b/Integrate.cpp new file mode 100644 index 0000000..f1e55dc --- /dev/null +++ b/Integrate.cpp @@ -0,0 +1,75 @@ +#include +#include +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'; +} \ No newline at end of file