我最近一直在努力学习更多有关lambda表达的知识,并想到了一个有趣的练习......
有没有办法简化这样的c ++集成函数:
// Integral Function double integrate(double a, double b, double (*f)(double)) { double sum = 0.0; // Evaluate integral{a,b} f(x) dx for(int n = 0 ; n <= 100; ++n) { double x = a + n*(b-a)/100.0; sum += (*f)(x) * (b-a)/101.0; } return sum; }
通过使用c#和lambda表达式?
那这个呢:
public double Integrate(double a,double b, Funcf) { double sum = 0.0; for (int n = 0; n <= 100; ++n) { double x = a + n * (b - a) / 100.0; sum += f(x) * (b - a) / 101.0; } return sum; }
测试:
Funcfun = x => Math.Pow(x,2); double result = Integrate(0, 10, fun);