//用弦截法求方程f(x)=x^3-5x^2+16x-80=0的根.
#include <stdio.h>
#include <math.h>
float f (float x) //定义f函数,以实现f(x)=x^3-5x^2+16x-80
{
float y;
y = ((x - 5.0)*x + 16.0)*x - 80.0;
return (y);
}
float xpoint (float x1, float x2) //定义xpoint函数,求出弦与X轴交点.
{
float y;
y = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
return (y);
}
float root (float x1, float x2) //定义root函数, 求近似根.
{
float x, y, y1;
y1 = f(x1);
do
{
x = xpoint (x1, x2);
y = f(x);
if (y * y1 > 0) //f(x)与f(x1)同符号.
{
y1 = y;
x1 = x;
}
else
x2 = x;
}
while (fabs (y) >= 1e-6);
return (x);
}
int main(void) //主函数.
{
float x1, x2, f1, f2, x;
printf ("input x1, x2: \n");
scanf ("%f, %f",&x1, &x2);
do
{
f1 = f(x1);
f2 = f(x2);
}
while (f1 * f2 >= 0);
x = root (x1, x2);
printf ("A root of equation is %8.4f", x);
getch ();
return 0;
}
它的根是5, 如果你输入的x1到 x2不包括5在内, 则得不到正确的结果. 如果你先不知道它的根是多少,怎么让别人知道需要输入多大的范围. 程式是否可以提示.
[此贴子已经被作者于2006-5-8 18:59:17编辑过]