用二分法求解方程解

作者在 2012-02-16 21:35:31 发布以下内容
#include <iostream>
#include <math.h>
#include <iomanip>
#define eps pow(0.1,6)//设定精度eps=0.00001
#define fx (x*x*x-2*x-5)//方程
using namespace std;
float f_x(float x)
{
    float a;
    a=fx;
    return a;
}
int main()
{
    float a,b,x;
    cout<<"输入方程解区间:"<<endl<<"a=";
    cin>>a;
    cout<<"b=";
    cin>>b;
    if(f_x(a)*f_x(b)<0)
    {
        do
        {
            x=(a+b)/2;
            if(f_x(a)*f_x(x)<0)//换掉一个半区间
            {
                b=x;
                if(fabs(b-a)<eps) break;
                else continue;
            }
            if(f_x(b)*f_x(x)<0)
            {
                a=x;
                if(fabs(b-a)<eps) break;
                else continue;
            }
        }
        while (f_x(x)!=0);
        cout<<"方程在精度为("<<eps<<")下的解为x="<<setprecision(15)<<(a+b)/2<<endl;
    }
    else if(f_x(a)*f_x(b)==0)
    {
        if(f_x(a)==0)
        cout<<"方程的解为x="<<setprecision(15)<<a<<endl;
        else
        cout<<"方程的解为x="<<setprecision(15)<<b<<endl;
    }
    else
    cout<<"方程在该区间下无解"<<endl;
    return 0;
}
文章评论,共0条
游客请输入验证码
浏览69231次