# c#求积分,1,2,3分别选择积分函数，错在哪里了

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 x, a, b,select;
double result;
Console.WriteLine("请选择要积分的函数 1:f(x)=1+x^2 2:f(x)=log10(x) 3:1/(1+x^2)");
Console.WriteLine("请输入积分上下限,x的值");

Integration func = new Integration();
func.fun_1(x);
func.fun_2(x);
func.fun_3(x);
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.SimpsonIntegral(a,b,0.0001,f1);
}
else if (select == 2)
{
result = func.SimpsonIntegral(a, b,0.0001, f2);
}
else
{
result = func.SimpsonIntegral(a, b,0.0001,f3);
}
Console.WriteLine("The result is {0}", result);
}
public delegate double FunctionDelegate(double x);
public 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 SimpsonIntegral(double a, double b, double eps, FunctionDelegate f)
{
int n, k;
double h, t1, t2, s1, s2, ep, p, x;
n = 1; h = b - a;
t1 = h * (f(a) + f(b)) / 2.0;
s1 = t1;
ep = eps + 1.0;
while (ep >= eps)
{
p = 0.0;
for (k = 0; k <= n - 1; k++)
{
x = a + (k + 0.5) * h;
p = p + f(x);

}
t2 = (t1 + h * p) / 2.0;
s2 = (4.0 * t2 - t1) / 3.0;
ep = Math.Abs(s2 - s1);
t1 = t2; s1 = s2; n = n+n; h = h / 2.0;
}
return s1;
}

}
}
``````

}

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进