北大OpenJudge 4140:方程求解

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37618760/article/details/83151614

4140:方程求解

总时间限制: 

1000ms

内存限制: 

65536kB

描述

求下面方程的根:f(x) = x3- 5x2+ 10x - 80 = 0。

输入

-

输出

精确到小数点后9位。

样例输入

-

样例输出

-

解析:属于二分思想的简单应用,首先我们设定初始的左右端点为0,100,root就取它们两个的二分点,然后带入f函数进行计算,如果说这个值是大于零的,我们就缩小右端点;反之,我们缩小左端点,最后求出方程的解。

源代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
double EPS = 1e-9;
double f(double x){
    return x*x*x-5*x*x+10*x-80;
}
int main(){
    double root,x1=0,x2=100,y;
    root=x1+(x2-x1)/2;
    int triedTimes =1;
    y=f(root);
    while(fabs(y)>EPS){
        if(y>0) x2=root;
        else  x1=root;
        root=x1+(x2-x1)/2;
        y=f(root);
        triedTimes++;
    }
    printf("%.9f\n",root);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37618760/article/details/83151614