题目
{% raw %}
{% endraw %}
用二分法求方程f(x)=ax4+bx3+cx2+dx+e=0 在 (x1,x2) 之内的根
本题保证f(x1)*f(x2)<=0且(x1,x2)内只有一个根
{% raw %}
{% endraw %}
行1:5个空格分隔的整数a,b,c,d,e,a,b,c,d,e∈[-9,9]
行2:2个空格分隔的整数x1,x2,x1,x2∈[-10,10],x1<x2
{% raw %}
{% endraw %}
行1:一个浮点数,代表根,精确到小数点后10位
{% raw %}
{% endraw %}
0 2 -4 3 -6
-10 10
{% raw %}
{% endraw %}
2.0000000000
{% raw %}
题解
由于最后要输出 10 位,因此 eps 至少要是 1e-11
然后就是模拟数学运算即可
为了防止错误,建议全部使用 double
数学函数部分可以写成一个函数或者宏定义,简化代码
没什么要注意的细节,知道数学计算思路就行
代码
```cpp 二分法求方程的根 https://github.com/OhYee/sourcecode/tree/master/ACM 代码备份
//*/
#define debug
#include
//*/
#include
#include
#include
#include
#include
using namespace std;
const double eps = 1e-12;
#define f(x) axxxx + bxxx+cxx+dx+e
bool equal(double a,double b) {
return fabs(a - b) < eps;
}
int main(){
#ifdef debug
freopen("in.txt", "r", stdin);
int START = clock();
#endif
cin.tie(0);
cin.sync_with_stdio(false);
double a,b,c,d,e,x1,x2;
while(cin >> a >> b >> c >> d >> e >> x1 >> x2){
double x = (x1+x2)/2;
double y1 = f(x1);
double y2 = f(x2);
//cout << "y1 = "<<y1<<" y2 = "<<y2<<endl;
while(1){
x = (x1+x2)/2;
double y = f(x);
//cout << "x = "<<x<<" y = "<<y<<endl;
getchar();
if(equal(0.0,y))
break;
if(y*y1 < 0)
x2 = x;
else
x1 = x;
}
cout << fixed << setprecision(10) << x << endl;
}
#ifdef debug
printf("Time:%.3fs.\n", double(clock() - START) / CLOCKS_PER_SEC);
#endif
return 0;
}
</div>