二分 - bailian 4140:方程求解

题目链接

http://bailian.openjudge.cn/practice/4140/
这个题给出的函数是一个单调函数,用数学中的二分法可以求解,这个题需要注意精度问题,题目要求保留9位小数,在误差的选择上需要注意,这里我用的是eps = 1e-8。

cpp代码

#include <cstring>
#include <cstdio>
#include <cmath>

double EPS = 1e-8;

double f(double x){
    return x*x*x - 5*x*x + 10*x - 80;
}

int main(){
    double l = 0, r = 10;
    double root = (l + r)/2;
    while(fabs(f(root)) > EPS){
        if(f(root) > 0)
            r = root;
        else
            l = root;
        root = (l + r) /2;
    }
    printf("%.9f\n", root);
}
posted @ 2020-04-01 18:28  zhangyue_lala  阅读(131)  评论(0编辑  收藏  举报