二分法算一元三次方程

题:

   用二分法求方程f(x)=x^3-2*x-1=0在[0,2]内的根,并输出每次二分的结果,精确到1e-4.

程序流程图见下:(流程图出自《计算方法》——江西高校出版社)

二分法算一元三次方程

代码:

#include <iostream>
using namespace std;
#include<math.h>
#include<iomanip>

int main()
{
    int i = 0;
    double a=0, b=2, c=1e-4,x,y;
    cout << setw(3) << 'i' << ' ' << setw(10) << 'x' << ' ' << setw(10) << 'y' << ' ' << setw(10) << 'a' << ' ' << setw(10) << 'b' << endl;
    for(i=0;i<100;i++)//随意地定义的循环,100无实际含义
    {
        x = (a + b) / 2;
        y = x * x * x - 2 * x - 1;
        if (abs(y) > c)//如果f(x)不满足精度要求
        {
            if (y < 0)//因为f(0)=-1,为负数,故y<0即表示,当f(a)与f[(a+b)/2]异号时
            {
                a = x;
            }
            else
                b = x;
            if (abs(b - a) <= c)//如果|b-a|<=1e-4
                break;
        }
        else
            break;
        cout <<setiosflags(ios::fixed)<<setprecision(7)<<setw(3)<<i<< ' ' <<setw(10)<< x << ' ' << setw(10) << y << ' ' << setw(10) << a << ' ' << setw(10) << b << endl;cout <<setiosflags(ios::fixed)<<setprecision(7)<<setw(3)<<i<< ' ' <<setw(10)<< x << ' ' << setw(10) << y << ' ' << setw(10) << a << ' ' << setw(10) << b << endl;
    }
    cout << setiosflags(ios::fixed) << setprecision(7) << setw(3) << i << ' ' << setw(10) << x << ' ' << setw(10) << y << ' ' << setw(10) << a << ' ' << setw(10) << b << endl;
    return 0;
}

结果图:

二分法算一元三次方程