已知方程X^3+X-4=0在区间[1,2]内有一根,用二分法求根,使其具有5位有效...
发布网友
发布时间:2024-02-10 17:24
我来回答
共1个回答
热心网友
时间:2024-07-20 03:30
#include <math.h>
#include <stdio.h>
double fun(double x) { return x * x * x + x - 4; }
int num=0;
double root(double a, double b, double e)
{
double x1, x2, y1, x, y;
x1 = a; x2 = b;
do {
x = (x1 + x2)/2;
y = fun(x);
y1 = fun(x1);
if( ( y < 0 && y1 < 0) || (y > 0 && y1 > 0) )
x1 = x;
else
x2 = x;
/*end if*/
num++;
}while(fabs(y) > e);
return x;
}
int main(void)
{
double x = root(1.0f, 2.0f, 1e-4);
printf("%.4f %d\n", x,num);
return 0;
}
/*
运行结果:
1.3788 13
*/