用c++解决:已知方程x^3-3x^2+6x-1=0在区间(0,1)上有解,用二分法的知识,求过程

要有过程,求高手帮忙解决
求根的近似值,误差不超过0.001

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

double func(double x)
{
return pow(x,3)-3*pow(x,2)+6*x-1;
}

int main()
{
double midx, midy, x1 =0.0, x2 = 1.0;
do
{
midx = (x1 + x2) / 2;
x2 = (func(midx) > 0)?midx : x2;
x1 = (func(midx) <= 0)?midx : x1;
}while(fabs(func(midx))>= pow(10.,-3));
cout<<midx<<endl;
cin.get();
return 0;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2011-03-15
#include <iostream>
#include <cmath>
using namespace std;

double f(double x)
{
return x*(x*(x-3)+6)-1;
}

int main()
{
double x0, x1=0, x2=1, f0, f1, f2, er = 0.001;

f1 = f(x1);
f2 = f(x2);
while ( x2 - x1 > er)
{
x0 = ( x1 + x2) / 2;
f0 = f(x0);
if( f0 * f1 < 0)
{
x2 = x0;
f2 = f0;
}
else
{
x1 = x0;
f1 = f0;
}
}
cout<<"root = "<<(x1+x2)/2<<endl;
return 0;
}
相似回答