1. 已知方程x2-x-2=0在区间[1,4]内有一实根。以下程序中的函数double root(double a,double b)为递归函数,采用二分法(半分区间法)求方程f(x)=0在区间[a,b]内的一个实根x,当|f(x)|<0.000001时,x即为所求的近似根。
为使程序具有通用性,方程各项的系数依次存储在一维数组coef[]中
//零点存在定理找根
#include<iostream>
#include<cmath>
using namespace std;
double f(double x,double coef[]){
return coef[0]*x*x - coef[1]*x - coef[2];
}
double root(double a, double b, double coef[]){
double m, f0, x;
m =(a+b)/2;
f0=f(a, coef);
x=0;
if(fabs(f(m, coef))<1e-6)
x=m;
else {
if( f0*f(m, coef)>0) a=m;//同号,无根
else b=m;
x=root(a, b, coef);
}
return x;
}
int main(){
double coef[]={1,-1,-2};
cout<<"One root is "<<root(1,4,coef) <<endl;
return 0;
}