用弦截法求方程x^3+ax^2+bx+c=0的根:(其中要求用户输入的x1和x2是用户估计的根的区间)
#include <stdio.h>
#include <math.h>
float a,b,c;
/*求f(x)=x^3+ax^2+bx+c=0的函数值。*/
float f(float x)
{
float y;
y=x*x*x+a*x*x+b*x+c;
return(y);
}
/*求(x1,f(x1))和(x2,f(x2))的连线与x轴的交点横坐标:x=[x1×f(x2)-x2×f(x1)] / [f(x2)-f(x1)]*/
float xpoint(float x1,float x2)
{
float x;
x=(x1*f(x2)-x2*f(x1))/(f(x2)-f(x1));
return(x);
}
/*求(x1,x2)区间内方程的实根*/
float root(float x1,float x2)
{
float x;
do
{
x=xpoint(x1,x2);
if(f(x)*f(x1)>0) x1=x;
else x2=x;
} while(fabs(f(x))>=1e-4);
return(x);
}
main()
{
float x1,x2,x;
printf("Please input a: ");
scanf("%f",&a);
printf("Please input b: ");
scanf("%f",&b);
printf("Please input c: ");
scanf("%f",&c);
do
{
printf("Please input x1 and x2: ");
scanf("%f%f",&x1,&x2);
}while(f(x1)*f(x2)>=0);
x=root(x1,x2);
printf("A root of equation is %.4f\n",x);
}
例如,a,b,c分别输入-5 16 -80,x1和x2分别输入1 10,结果为5
温馨提示:答案为网友推荐,仅供参考