parent
95167417cb
commit
3e9220b1b4
@ -0,0 +1,31 @@
|
||||
#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>
|
||||
double integrate(T cf, double a, double b, int n = 10000)
|
||||
{
|
||||
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()
|
||||
{
|
||||
std::cout << integrate<F1>(F1{}, 0, 1) << '\n';
|
||||
std::cout << integrate<F2>(F2{}, 0, 1);
|
||||
}
|
Loading…
Reference in new issue