POJ 4140:方程求解
看了模板之后也没有思路,于是直接看了题解:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
double search(double left,double right)
{
double mid;
double f;
while(right-left>1e-11)
{
mid=left+(right-left)/2;
f=mid*mid*mid-5*mid*mid+10*mid-80;
if(f<0)
left=mid;
else
right=mid;
}
return mid;
}
int main()
{
printf("%.9lf\n",search(0.0,10.0));
return 0;
}
下面没有用模板,更好理解,但也是二分的思路:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
int main()
{
double EPS=1e-11;
double left=0,right=10,f;//f=f(mid)
double mid=left+(right-left)/2;
f=mid*mid*mid-5*mid*mid+10*mid-80;
while(fabs(f)>EPS)
{
if(f>0) right=mid;
else left=mid;
mid=left+(right-left)/2;
f=mid*mid*mid-5*mid*mid+10*mid-80;
}
printf("%.9lf\n",mid);
return 0;
}
hh