代码如下,其中代码中系数已指定
#include
#include
void main()
{
float f(float x);
float root(float x1, float x2);
float xpoint(float x1,float x2);
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);
}
float root(float x1, float x2)
{
float xpoint(float x1,float x2);
float f(float x);
int i;
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);
}
float f(float x)
{
float y;
y=((x-5.0)*x+16)*x-80;
return (y);
}
float xpoint(float x1,float x2)
{
float y;
y=(x1*f(x2)-x2*f(x1)) / (f(x2) - f(x1));
return (y) ;
}
楼上的程序有问题,只要第二个数字大于18结果就出不来了;现修改如下;
#include
#include
double xpoint(double x,double y);
double f(double x);
double boot(double x,double y);
int main()
{
double x1,x2,z;
do
{
scanf("%lf %lf",&x1,&x2);
}while((x1>x2)||(f(x1)*f(x2)>0));
z=boot(x1,x2);
printf("%lf\n",z);
return 0;
}
double f(double x)
{
return (x*(x*x-5*x+16)-80);
}
double xpoint(double x,double y)
{
return(x*f(y)-y*f(x))/(f(y)-f(x));
}
double boot(double x,double y)
{
double z;
do
{
z=xpoint(x,y);
if(f(x)*f(y)>0)
x=z;
else
y=z;
}while(fabs(f(z))>0.000001);
printf("\a");
return (z);
}