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.
31 lines
573 B
31 lines
573 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>
|
|
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);
|
|
} |