【发布时间】:2021-12-30 06:37:18
【问题描述】:
我使用二分法找到方程的解。
我需要在一些迭代中找到 a 和 b 的值。因此,我分别为这些点做了两个数组。
为了从函数中“提取”迭代次数,我没有问题。它们显示在屏幕上。但是我如何“拉出”这两个数组?请告诉我该怎么做。提前谢谢!
double f1(double x){
return x*x-5*sin(x);
}
double f2(double x){
return exp(x)-pow(10,x);
}
double f3(double x){
return sin(x)-x+0.15;
}
double f4(double x){
return x-pow(9+x,0.5)+x*x-4;
}
double dihotom (double a , double b , double e , double(*fp)(double),int &iter,double &points_a[],double &points_b[]){
double c , fc , fa = fp(a);
iter=(log10((b-a)/e))/log10(2);
int step = iter/3;
int step_current = step;
int it=0;
int k=0;
do{
c=(a+b)/2;
fc=fp(c);
if (fa*fc<=0) b = c ; else a = c;
it++;
if(it==step_current){
points_a[k]=a;
points_b[k]=b;
k++;
step_current=step_current+step;
}
fa=fp(a);
printf ("it %d: a = %lf,b = %lf\n",iter,a,b);
}while (fabs(a-b)>=e);
return c;
}
int main(int argc, char *argv[]) {
int int_s=0;
double points_a[3];
double points_b[3];
double k3= dihotom (0.5,1,0.0001,f3,int_s,points_a[3],points_b[3]);
printf("For F3 - root = %lf, F3(%.2lf)=%lf ;iter =%d\n", k3, k3 ,f3(k3),int_s);
int i=0;
for(i=0;i<3;i++){
printf("step : %d , a: %lf, b: %lf ", i,points_a[i],points_b[i]);
}
return 0;
}
【问题讨论】:
-
@drescherjm 那我该怎么做呢?
-
但是我如何“拉出”这两个数组呢? -- 我不知道这应该是什么意思。如果要返回多个值,请声明具有多个值的
struct并返回struct的实例。 -
您可能想要
double (&points_a)[3]或double points_a[]。 -
如果你想将数组作为参数传递,你必须自己指定数组:
,points_a,points_b,而不是,points_a[3],points_b[3] -
我删除了 2 个数组上的引用并修复了缺少的包括:https://ideone.com/4NZwcK