xaml代码:

    <Grid>
        <StackPanel>
            <Button Name="solve" Width="120" Height="30" Margin="30,30,0,0" Click="solve_Click">求解</Button>
            <TextBox Name="txb" Width="120" Height="30" Margin="30,30,0,0"></TextBox>
        </StackPanel>
    </Grid>

C#二分法求方程的根_求解

自定义函数代码:

        static double TargetFunction(double x)
        {
            // 示例函数:
            return x*x*x  - 1;
        }

二分法求方程的根:

        static double BinarySolve(double start,double end,double delt)
        {
            double mid;

            while(Math.Abs( end-start)>delt)
            {
                mid = (start + end) / 2;

                if (TargetFunction(mid) == 0)
                {
                    
                    return mid;
                }
                else if (TargetFunction(start) * TargetFunction(mid) > 0)
                { 
                    start = mid;
                }
                else if(TargetFunction(start) * TargetFunction(mid) < 0)
                {
                    end=mid;
                }
            }

            return (start + end) / 2;
            
        }

按钮“求解”实例:

        private void solve_Click(object sender, RoutedEventArgs e)
        {
            double start = -2;

            double end = 10;

            double delt = 0.00001;

            double sol = BinarySolve(start, end, delt);

            txb.Text = sol.ToString();
        }

C#二分法求方程的根_求解_02