三次方程求法

#include <iostream.h>
#include <math.h>
#include <iomanip>
#include <fstream.h>
#include <stdlib.h>

#define f(x) (1*x*x*x-3*x*x-6*x+8)

double bisection(double x,double y,double z)
{
double a=x,b=y,p;
while(((b-a)/2)>=z)
{ p=(a+b)/2;
if(f(p)*f(b)<=0)
a=p;
else b=p;
}
return p;

}

void main()
{
double a[5];
char filename[256];
cout.setf(ios::fixed);
cout<<"请输入误差容限:";
cin>>a[0];
cout<<"输入目的文件全路径:";
cin>>filename;
ofstream outfile(filename);
a[2]=(3-sqrt(21))/2;
a[3]=(3+sqrt(21))/2;
a[1]=a[2];
a[4]=a[3];
for(int i=1; ;i++)
{
if(f(a[1])>=0) a[1]--;

else if(f(a[4])<=0) a[4]++;
else break;
}
for(i=1;i<4;i++)

outfile<<"函数f(x)在区间("<<a[i]<<’,’<<a[i+1]<<")上的根为"<<bisection(a[i],a[i+1],a[0])<<endl;

cout<<"已经将结果写入:"<<filename<<endl;
cout<<"误差在"<<a[0]<<"之内."<<endl;
outfile.close();
}

input=============

f:output.txt //可以是任何路径
1e-7

output============

函数f(x)在区间(-2.79129,-0.791288)上的根为-2
函数f(x)在区间(-0.791288,3.79129)上的根为1
函数f(x)在区间(3.79129,4.79129)上的根为4

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注