您的位置:首页 > 编程语言 > C#

C# - 委托_求定积分通用方法

2015-05-24 15:46 381 查看
代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 委托_例子
{
static class Program
{
// 定义委托(Double类型)
delegate double Integand(double x);

//定义方法
static double Method1(double x)
{
return 2 * x + 1;
}

static double Method2(double x)
{
return x * x;
}

// 定义是用委托的方法
static double DefiniteIntegrate(Integand f, double a, double b)
{
const int sect = 1000;

double area = 0;

double delta = (b - a) / sect;

for (int i = 0; i < sect; i++)
{
//此处的 f 就代表 Method1 或是 Method2。
//传给他们一个double类型的值,返回一个double类型的值。
//此时的double值就是长乘以宽“a + i * delta”
area += delta * f(a + i * delta);
}

return area;
}

static void Main(string[] args)
{
//调用方法
//传入一个方法
Console.WriteLine(Program.DefiniteIntegrate(Method1, 1, 5));
Console.WriteLine();
Console.WriteLine(Program.DefiniteIntegrate(Method2, 0, 1));

Console.ReadKey();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: