Charles_Su 2016-06-29 02:04 采纳率: 21.4%
浏览 724

c#辛普森法求积分,可以选择函数,问题出在哪里了

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;
        }

    }
}

}

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀
    • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
    • ¥15 关于#hadoop#的问题
    • ¥15 (标签-Python|关键词-socket)
    • ¥15 keil里为什么main.c定义的函数在it.c调用不了
    • ¥50 切换TabTip键盘的输入法