我试图在C语言中实现Bolzano的二等分方法,虽然该算法看起来有效,但它在大约4个步骤后意外终止
第四步似乎是增加“err”和“divid”,而不是不断减少。我试图使代码尽可能简单,所以main中没有指针/引用/数组/参数等。
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
//#define delta 0.00000000005
//#define epsilon 0.000000000005
//#define root1 1
//#define root2 -1
//#define maxit 7000
void bolzano(double a,double b, float root);
double function(double x);
int counter = 0;
//double err_global;//eps = 0.5e-6;
double maxit = 300;
double epsilon = 0.5E-6;
double delta = 0.5E-10;
int root1 = 1;
int root2 = -1;
int main(void){
double a,b;
printf("Eisagete tis times toy diastimatos [a,b]: ");
scanf("%lf%lf",&a,&b);
printf("[a,b] = [%lf \\,%lf]\n",a, b);
printf(" ksi = %d\n", root1);
printf(" n Xn En En+1/En");
bolzano(a,b,root1);
system("pause");
printf("[a,b] = [%lf \\, %lf]\n",a, b);
printf(" ksi = %d", root2);
bolzano(a,b,root2);
system("pause");
return 0;
}
double function(double x){
return pow(x-1,3) * (x+1);
}
void bolzano(double a, double b, float root){
double c,err,divit,err_global;
while(b - a > epsilon && counter < maxit){
//system("pause");
c = (a + b)/2;
err = fabs(c - root);
if(counter == 0 ){
err_global = err;
printf(" %d %lf %lf \n", counter, c, err);
counter++;
if(function(a) * function(c) < 0){
b = c;
continue;
}
else{
a = c;
continue;
}
}
divit = err/err_global;
printf(" ");
printf(" %d %lf %lf %lf\n",counter, c ,err, divit);
err_global = err;
if(fabs(function(c)) < delta){
break;
}
else if(function(a) * function(c) < 0){
counter++;
b = c;
//continue;
}
else{
counter++;
a = c;
//continue;
}
}
}
最佳答案
你用的是全球
int counter = 0;
控制功能
bolzano
中的操作,该功能永远不会重置。请在
bolzano
开头添加这一行counter = 0;