您的位置:首页 > 其它

用弦截法求一元三次方程的根

2012-07-15 10:09 766 查看
网上好多人这样写,经过测试,当第二个数大于6时,程序就出错了,我纠结了一下午,原来是float的问题:把float改为double就好了,第二个代码可以解释为什么.

#include<math.h>
#include<stdio.h>

float f(double 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;
y1=f(x1);
do
{
x=xpoint(x1,x2);
y=f(x);

if(y*y1>0)
{
y1=y;
x1=x;
}
else
x2=x;
printf("%f\n",fabs(y));
}while(fabs(y)>0.000001);

return x;
}

void main()
{
float x,x1,x2,y1,y2;
do
{
printf("INPUT X1,X2:\n");
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);

}


#include<stdio.h>
int main()
{
float i;
i=0.0000000000000000000000000000000000001;
printf("%f\n",1/3);
printf("%e\n",1/3);
printf("%f\n",1.5/3);
printf("%e\n",1.5/3);
printf("%f\n",0.0000001);        //打印0.000000
printf("%e\n",i);
printf("%f\n",0.00000001);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: