其他分享
首页 > 其他分享> > c 二分法求方程近似解

c 二分法求方程近似解

作者:互联网

 

 

 

 

 

 

 

 

 

 

 

 

#include <stdio.h>
#include <math.h>
#define EPSILON 1e-7

double bisection(int p, int q, double (*func)(int, int, double));
double f(int p, int q, double x);
int main() {
    int p;
    int q;
    scanf("%d%d", &p, &q);
    printf("%.4lf\n", bisection(p, q, f));
    return 0;
}

double bisection(int p, int q, double (*func)(int, int, double)) {

    double x1 = -20;
    double x2 = 20;
    double x = 0;
    while(fabs((*func)(p,q,x))>EPSILON)
    {
        x = (x1+x2)/2.0;
        double fx1 = (*func)(p,q,x1); 
        double fx =  (*func)(p,q,x);
        if(fx*fx1>0)
        {x1 = x;}
        else
        {x2 = x;}
        
    }
    return x;
  

     
}

double f(int p, int q, double x) {
    return p * x + q;
}

 

标签:方程,return,int,double,近似,二分法,bisection,func,x1
来源: https://www.cnblogs.com/qingjiawen/p/15073428.html