一、弦截法求方程根
二、算法(见教材)
三、编程实现
/*
(1)代码中用函数发f(x)代表x的函数
(2)用函数xpoint(x1,x2)来求(x1,f(x1))和(x2,f(x2))的连线与x轴的交点x的坐标。
(3)用函数root(x1,x2)来求(x1,x2)区间的那个实根。
*/
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
double f(double); //函数声明
double xpoint(double,double);//函数声明
double root(double,double);//函数声明
int main()
{
double x1,x2,f1,f2,x;
do
{
cout<<"input x1,x2: ";
cin>>x1>>x2;
f1=f(x1);
f2=f(x2);
if (f1*f2>=0)
cout<<"f1,f2同符号,继续取值:\n";
else
break;
}while(f1*f2>=0); //当f1、f2的乘积为正值时,说明条件不满足,需要进一步确定x1,x2的取值
cout<<"f1,f2取值符合条件,开始计算函数根:\n";
x=root(x1,x2);
cout<<setiosflags(ios::fixed)<<setprecision(7); //指定输出7位小数
cout<<"A root of equation is "<<x<<endl;
return 0;
}
double f(double x) //定义f函数,以实现f(x)
{
double y;
y=x*x*x-6*x*x+16*x-80;
return y;
}
double xpoint(double x1, double x2)
{
double y;
y=(x1*f(x2)-x2*f(x1))/(f(x2)-f(x1));
return y;
}
double root(double x1, double x2)
{
double x,y,y1;
y1=f(x1);
do
{
x=xpoint(x1,x2);
y=f(x);
if(y*y1>0)
{
y1=y;
x1=x;
}
else
x2=x;
}while(fabs(y)>=0.00001);
return x;
}