大家能帮我看看这段算法?

来源:百度知道 编辑:UC知道 时间:2024/07/04 13:32:48
用二分法设计一个通用函数root(),求方程f(x)=0在【a,b】内的
一个实根(设f(a)f(b)<0),要求根的精度为10的-8次方。并用root()
函数求x*x*x-6*x-1=0在x=2附近的实根。
#include <iostream>
#include <cmath>
using namespace std;

double equation(double x)
{return x*x*x-6*x-1;}

double root(double a,double b)
{double (*f)(double);
*f=equation;
while(b-a>10e-8)
{if(f((a+b)/2)>0) b=(a+b)/2;
else a=(a+b)/2;
}
return (a+b)/2;
}

int main(void)
{cout<<"方程在x=2附近的一个实数:"<<root(2.0,3.0);
return 0;
}
为啥这个只有5位

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

double equation(double x)
{
return x*x*x-6*x-1;

}

double root(double a,double b)
{
double (*f)(double);
f=equation;
while((b-a)>10e-8)
{if(f((a+b)/2)>0)
b=(a+b)/2;
else
a=(a+b)/2;
}
return (a+b)/2;
}

int main(void)
{
cout<<setiosflags(ios::fixed)<<setprecision(8)<<"方程在x=2附近的一个实数:"<<root(2.0,3.0);
return 0;
}