注册 登录
编程论坛 C++教室

我的弦截法求大神拯救

okauld 发布于 2012-11-06 12:25, 278 次点击
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
float f(float x)
{
    float y;
    y=((x-5.0)*x+16.0)*x-80.0;
    return y;
}
  
  
float xpoint(float x1,float x2)
{
    float x;
    x=(x1*f(x2)-x2*(x1))/(f(x2)-f(x1));
    return x;
}

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

int main()
{
    float x1,x2,f1,f2,x;
    do
      {
          printf("input x1,x2:\n");
          scanf("%f,%f",&x1,&x2);
          f1=f(x1);
          f2=f(x2);
      }
    while(f1*f2>=0);
    x=root(x1,x2);
    printf("A root of equation is %8.4f\n",x);
    system("pause");
    return 0;
}                  
1 回复
#2
rjsp2012-11-06 14:10
快速一览
x=(x1*f(x2)-x2*f(x1))/(f(x2)-f(x1));

为什么用float,而不是double?
1