一. 二分法
题目:用二分法求方程x3-2x-5=0在区间【2,3】内的一个实根,要求误差不超过0.01.
1 #include <iostream> 2 using namespace std; 3 4 double f(double x) 5 { 6 return x*x*x - 2*x - 5; 7 } 8 9 int main() 10 { 11 double left = 2.0, right = 3.0; 12 double mid; 13 while(right - left > 0.01) 14 { 15 mid = (right + left)/2; 16 if(f(mid) == 0) 17 break; 18 if(f(mid)*f(left) > 0) 19 left = mid; 20 else 21 right = mid; 22 } 23 cout<<mid<<endl; 24 return 0; 25 }
时间: 2024-10-07 21:08:15