# c#用复合梯形公式求积分，已知上下限及步长为什么计算结果为0

charles_su
• 42

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)");
Console.WriteLine("请输入积分上下限及步长");
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);
}
//定义委托
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;
}

}
}
``````

}

2 个回答
✓ 已被采纳

``````    select = int.Parse(Console.ReadLine());
Console.WriteLine("请输入积分上下限及步长");