这个程序是用二分法求解方程给出错误“函数显示返回值”。
在这个方法中我们得到了一个函数 f(x)
我们近似 2 个根 a
和 b
对于这样的功能 f(a).f(b)<0
.
然后我们再找一个点
c=(a+b)/2
if f(c)==0
then root=c;
else
if f(a).f(c)<0
b=c;
if f(b).f(c)<0
a=c;
然后我们针对给定的迭代次数重复这些步骤
#include<stdio.h>
#include<math.h>
#define e 0.000001/*e is the prescribed accuracy*/
main()
{
double g1,g2,g,v,v1,v2,prev;
int found=0,converged=0,i=0;
double f(double);
printf("We apply Bisection method to find a real root of the non-linear equation f(x) = 0, where f(x) = x^(2.7182818)-3cosx+1n");
while(found==0)/*This loop will continue until a range is found in between which a real root lies*/
{
printf("nEnter the first guess : ");
scanf("%lf",&g1);
v1=f(g1);
printf("nEnter the second guess : ");
scanf("%lf",&g2);
v2=f(g2);
if(v1*v2>0)
{
found=0;
g1++;
printf("nRoot does not lie in [%lf,%lf].n",g1-1,g2);
printf("nn..Enter two new guesses..nn");/*Previous two guesses are inappropriate*/
}
else
found=1;
}
printf("nThere is a real root which lies in [%lf,%lf].n",g1,g2);
while(converged==0)/*This loop will continue until a real root is found*/
{
printf("nnIteration = %dnn",i);
printf("a[%d](-ve)tb[%d](+ve)tbbx[%d]=(a[%d]+b[%d])/2tf(x[%d])n",i,i,i+1,i,i,i+1);
printf("%lft",g1);
printf("%lft",g2);
g=(g1+g2)/2;
v=f(g);
printf("%lft",g);
printf("t%lf",v);
if(v<0)
g1=g;
else
g2=g;
if(fabs(prev-v)<e)
converged=1;
else
prev=v;
i=i+1;
}
printf("nnThe approximate value of the root is : %lfn",g);
}
/*This function returns values of f(x)*/
double f(double x)
{
return pow(2.7182818,x)-3*cos(x)+1;
}
最佳答案
当使用初始值 1 和 2 以及迭代 20 进行测试时,结果为 1.154172。这是系统的根。
当使用初始值 1、1 和迭代 20 进行测试时,结果为 1.0000,这是错误的。
您应该检查根的初始条件是否满足,即 f(a) * f(b) < 0。
f(1) = -1, f(1)* f(1) = +1,故第二种情况不满足初始条件。
关于二分法求解方程的C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32240918/