求下面一个方程的根: f(x)=x3−5x2+10x−80 f ( x ) = x 3 − 5 x 2 + 10 x − 80 如果a是方程的根,则要求 f(|a|)<=1e−6 f ( | a | ) <= 1 e − 6 通过对公式的求导可以发现,导函数开口向上,与x轴没有交点,那么导函数的值就是始终大于0的,所以原函数单调递增 而且已知 f(0)<0 f ( 0 ) < 0 , f(100)>0 f ( 100 ) > 0 我们采用二分的思想来解决问题
#include <iostream> #include <cstdlib> #include <cmath> #define EPS 1e-6 using namespace std; int count = 0; double f(double x){ return x*x*x-5*x*x+10*x-80; } int main(){ double min = 0; double max = 100; double mid ; while(true){ ++count; mid = (min + max) / 2; if(fabs(f(mid)) <= EPS ){ cout <<"times:" << count << " root:" << mid << endl; exit(0); } else if(f(mid) < 0){ min = mid; } else max = mid; } return 0; }中国大学mooc 程序设计与算法(二) 算法基础 https://www.icourse163.org/learn/PKU-1001894005?tid=1002445041#/learn/content?type=detail&id=1003540152