parent
3e9220b1b4
commit
921be2a20c
@ -0,0 +1,41 @@
|
||||
#include <iostream>
|
||||
#include <cmath>
|
||||
|
||||
// 用函数模板求解定积分
|
||||
class F1
|
||||
{
|
||||
public:
|
||||
double fun(double x) { return x * x; }
|
||||
};
|
||||
class F2
|
||||
{
|
||||
public:
|
||||
double fun(double x) { return x; }
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class Integrate
|
||||
{
|
||||
double a, b;
|
||||
int n;
|
||||
T cf; // 传递被积函数
|
||||
public:
|
||||
Integrate(double _a, double _b, int _n = 10000) : a{_a}, b{_b}, n{_n} {}
|
||||
double integrate()
|
||||
{
|
||||
double result{(cf.fun(a) + cf.fun(b)) / 2};
|
||||
double h{(b - a) / n};
|
||||
for (int i{1}; i < n; i++)
|
||||
result += cf.fun(a + i * h);
|
||||
result *= h;
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
Integrate<F1> i1{0, 1};
|
||||
Integrate<F2> i2{0, 1};
|
||||
std::cout << i1.integrate() << '\n'
|
||||
<< i2.integrate();
|
||||
}
|
Loading…
Reference in new issue