c#求积分,1,2,3分别选择积分函数,错在哪里了
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)");
select = Convert.ToInt32(Console.Read());
Console.WriteLine("请输入积分上下限,x的值");
a= Convert.ToInt32(Console.Read());
b= Convert.ToInt32(Console.Read());
x = Convert.ToInt32(Console.Read());
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);
System.Threading.Thread.Sleep(1000 * 1000);
}
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;
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论