本程序为本人参考一些资料后编写,在visual c++6.0下调试通过。
[@more@]////////////////
/////二分法求一个未知数方程的根f(x)=0
////////////////
#include
#include
using namespace std;
//////////
double fun(double x);
double RootByBisection(double(*pf)(double x),double a,double b,double err);
//////////
//////////
int main()
{
double a,b,err;
cout<<"请输入一元函数f(x)的定义域下界:a=";cin>>a;
cout<<"请输入一元函数f(x)的定义域上界:b=";cin>>b;
cout<<"请输入精度要求(推荐取err=1E-6):err=";cin>>err;
double root=RootByBisection(fun,a,b,err);
cout< cout<<"函数值f(x0)="< return 0;
}
//////////
////可以在下面修改函数
double fun(double x)
{
return (x*x*x-x-1);
}
//////////
double RootByBisection(double(*pf)(double x),double a,double b,double err)
{
double x1,x2;
x1=a;
x2=b;
while(fabs(x2-x1)>err)
{
if(pf(x1)*pf((x1+x2)/2)<0)
x2=(x1+x2)/2;
else
x1=(x1+x2)/2;
}
return (x1);
}
//////////
//////////
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/11355887/viewspace-974942/
,如需转载,请注明出处,否则将追究法律责任。