用二分法求2*x*x*x-4*x*x+3*x-6=0在(-10,10)之间的根。(用c语言编写)

来源:百度知道 编辑:UC知道 时间:2024/06/27 12:36:51
要用c语言编写。

楼上的类型不太好,改用实型的,不然会出错(实数根无法输出)。
还有cout是C++的吧,楼主要的是C
附上我的:
#include<stdio.h>
#include<math.h>
double calc(double x)
{
return ((2*x-4)*x+3)*x-6;
}
double root(double f,double t)
{
double mid=(f+t)/2.0,s=calc(mid);
while (fabs(s)>1e-6)
{
if (s>0) t=mid;
else f=mid;
mid=(f+t)/2.0;
s=calc(mid);
}
return mid;
}
int main()
{
printf("%lf\n",root(-10.0,10.0));
return 0;
}

运行结果:2.000000

double f(int x)
{
return 2*x*x*x-4*x*x+3*x-6;
}

double sol(int x,int y)
{
if (y-x<0.00001) return x/2+y/2;
if (f(x/2+y/2)>0)return sol(x,y/2+x/2);
else return sol(y/2+x/2,y);
}

main()
{cout<<sol(-10,10);}