24小时热门版块排行榜    

查看: 492  |  回复: 2

路过081001

铜虫 (正式写手)

[求助] 求高手,,C语言弦截法方程的根,我同谭浩强的视频程序几乎没有差别,为什么求不出呢

#include
#include

float f(float x)
{
        return ((x-5)*x+16)*x-80;
}

float xpoint(float x1,float x2)
{
return (x1*f(x2)-x2*f(x1))/(f(x2)-f(x1));

}


float root(float x1,float x2)
{  
  float x,y,y1,y2;
  y1=f(x1);y2=f(x2);
  do
  {
   x=xpoint(x1,x2);
   y=f(x);
   if(y*y1>0) {y1=y;x1=x;}
   else {x2=x;y2=y;}
  } while (fabs(y)>0.00001);
  return x;
}


void main()
{
float x,x1,x2,y1,y2;

  do
  { printf("input x1,x2:";
    scanf("%f,%f",&x1,&x2);
    y1=f(x1);
        y2=f(x2);
  } while(y1*y2>0);

x=root(x1,x2);

printf("A root is %f\n",x);

}
回复此楼
不要光上人人QQ,不然好没出息。
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

wpwupingwp

木虫 (正式写手)

南无观世音菩萨
2楼2012-11-18 17:29:48
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

chunyuan314

银虫 (正式写手)

LZ,问题出在root函数 do-while循环部分。
按弦截法,root函数可以这样:
float root(float x1,float x2)
{  
  float x,y,y1,y2;
  y1=f(x1);y2=f(x2);
   x=xpoint(x1,x2);
   y=f(x);
   if(fabs(y)<0.00001){ /* 如果精度达到,Okay */
       return x;
   }else if(y*y1>0){  /*即如果新的y与y1同号,则改为在x~x2之间用弦截法*/
       return root(x,x2);
   }else{
       return root(x1,x);  /*否则就在在x1~x之间用弦截法*/
   }
}

运行root(-10,10)可得到5

函数图形.png

Lifeisgood
3楼2013-01-29 20:09:10
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
相关版块跳转 我要订阅楼主 路过081001 的主题更新
信息提示
请填处理意见