二分法求根~~函数错呢??
老师布置的一个作业,用二分法求方程在1附近的实根,下面是程序:#include<iostream>
#include<cmath>
using namespace std;
float function(float y);
float eqRoot(float x1,float x2);
void main()
{ float x,x1,x2;
float y1,y2;
do
{ cout<<"输入x1,x2"<<endl;
cin>>x1>>x2;
y1=function(x1);
y2=function(x2);
}while(y1*y2>=0);
x=eqRoot(x1,x2);
cout<<"root:"<<x<<endl;
cout<<function(x)<<endl;
}
float function(float x)
{ float y=sin(x)+log(x)-exp(x)+x*x*x+1.260483;
return y;
}
float eqRoot(float x1,float x2)
{ float x,y,y1;
y1=function(x1);
x=(x1+x2)/2;
y=function(x);
while(fabs(y)>=0.000001)
{
if(y*y1>0)
{x1=x;
y1=y; }
else
x2=x;
x=(x1+x2)/2;
y=function(x);
}
return x;
}
我输入的是0.3,1.8,可计算结果x是0.774878,y是-8.97993Xe(-8),但用计算器算是-0.6861,请问是哪错呢?
谢谢