这个二分法解方程错在什么地方?

来源:百度知道 编辑:UC知道 时间:2024/06/04 08:43:45
很明显方程的根是5,但是我输入0和10得到的结果不正确,而且结果受到输入值的影响

//二分法解方程的根
#include<iostream.h>
#include<math.h>

double f(int x);
void main()
{ double proot1,proot2;
double root;
do{
cout<<"enter one possible root:";
cin>>proot1;
cout<<"enter another possible root";
cin>>proot2;
}while(f(proot1)*f(proot2)>0&&proot1>proot2);

root = (proot1+proot2)/2;
do
{

if(f(root)*f(proot2)<0)
proot1=root;
if(f(root)*f(proot1)<0)
proot2=root;

root = (proot1+proot2)/2.0;
}while(fabs(f(root))>0.00001);

cout<<"genshi"<<root;

}

double f(int x)
{
return x*x*x-5*x*x+16*x-80;
}

程序只需将double f(int x)
改为double f(double x) 即可
另外程序中需要考虑一开始输入的数值即为根的情况
还有就是while(f(proot1)*f(proot2)>0&&proot1>proot2);
中的判断条件没有必要吧?不应该限制一开始用户输入数据的顺序。