2-3 二分法求函数的零点(25分)
有函数:
已知f(1.5)>0,f(2.4)<0 且方程f(x)=0 在区间[1.5,2.4] 有且只有一个根,请用二分法求出该根。 提示:判断函数是否为0,使用表达式 fabs(f(x)) < 1e-7
输入格式:
无。
输出格式:x
该方程在区间[1.5,2.4]中的根。要求四舍五入到小数点后6位。。
输入样例:
无
输出样例:
无
#include <bits/stdc++.h>
#define E 1e-7
using namespace std;
double f(double x)
{
return x*x*x*x*x-15*x*x*x*x+85*x*x*x-225*x*x+274*x-121;
}
double binarysearch(double l, double r)
{
while(l+E<r){
double m = (l+r)/2.0;
if(f(l)<=E && f(l)>=(-E)) return l;
else if(f(r)<=E&& f(r)>=(-E)) return r;
if(f(m)<=E&& f(m)>=(-E)) return m;
if(f(m)>0) l=m;
else r=m;
}
}
int main()
{
double l=1.5, r=2.4;
double a = binarysearch(l,r);
cout <<fixed<< setprecision(6) << a <<endl;
}
注意有fixed和没有fixed的区别