using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a, b, select;
double result,step;
Console.WriteLine("请选择要积分的函数,1:f(x)=1+x^2 2:f(x)=log10(x) 3:1/(1+x^2)");
select = Console.Read();
Console.WriteLine("请输入积分上下限及步长");
a = Console.Read();
b = Console.Read();
step = Console.Read();
Integration func = new Integration();
FunctionDelegate f1 = new FunctionDelegate(func.fun_1);
FunctionDelegate f2 = new FunctionDelegate(func.fun_2);
FunctionDelegate f3 = new FunctionDelegate(func.fun_3);
if (select == 1)
{
result = func.Integral(a, b,step, f1);
}
else if (select == 2)
{
result = func.Integral(a, b, step, f2);
}
else
{
result = func.Integral(a, b,step, f3);
}
Console.WriteLine("The result is {0}", result);
System.Threading.Thread.Sleep(1000 * 1000);
}
//定义委托
public delegate double FunctionDelegate(double x);
public partial class Integration
{
public double fun_1(double x)
{ return 1 + x * x; }
public double fun_2(double x)
{ return Math.Log10(x); }
public double fun_3(double x)
{ return 1 / (1 + x * x); }
public double Integral(double a, double b,double s, FunctionDelegate f)
{//梯形法求积分的值
double sum = 0;
for(double i=a; i<=b; i+=s)
{
sum += f(i);
}
sum *= s;
return sum;
}
}
}
}