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.
42 lines
770 B
42 lines
770 B
#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();
|
|
}
|