二分法求函数根的原理为:如果连续函数f(x)f(x)在区间[a, b][a,b]的两个端点取值异号,即f(a)f(b)<0f(a)f(b)<0,则它在这个区间内至少存在1个根rr,即f(r)=0f(r)=0。
二分法的步骤为:
输入样例:
3 -1 -3 1
-0.5 0.5
输出样例:
0.33
#include <stdio.h>
double f(double a[],double x);
int main (){
double a[4];
int i;
for(i=3;i>=0;i--){
scanf("%lf",&a[i]);
}
double low,high;
scanf("%lf %lf",&low,&high);
double mid=(low+high)/2;
while(f(a,mid)!=0&&(high-low)>0.001){
if(f(a,low)==0){
mid=low;
break;
}
if(f(a,high)==0){
mid=high;
break;
}
if(f(a,mid)*f(a,low)>0){
low=mid;
}
else{
high=mid;
}
mid = (low + high) / 2;
}
printf("%2f\n",mid);
return 0;
}
double f(double a[],double x){
return a[3]*x*x*x+a[2]*x*x+a[1]*x+a[0];
}