关于用弦截法求根的问题
第一个代码是我自己写的,是正确的,能得到答案,第二个贴的是书上的答案,但是得不到正确答案,代码都是一样的,只是几个函数定义的位置不同,我的函数定义在后面,而答案的函数定义在前面,为什么得不到结果程序代码:
#include "stdio.h" #include "math.h" int main(void) { float x1, x2, f1, f2, x; float f(float x); /*求函数值*/ float xpoint(float x1, float x2); /*求中间变量X*/ float root(float x1, float x2); /*求根*/ do { printf("Please input two numbers :\n"); scanf("%f%f", &x1, &x2); f1 = f(x1); f2 = f(x2); } while (f1*f2 >= 0); x = root(x1, x2); printf("%f", x); return 0; } float f(float x) { float y; y = x*x*x - 5.0 * x*x + 16.0 * x - 80.0; return (y); } float xpoint(float x1, float x2) { float y; y = (x1*f(x2) - x2*f(x1)) / (f(x2) - f(x1)); return (y); } 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) { x1 = x; y1 = y; } else { x2 = x; } } while (fabs(y) >= 0.0001); return (x); }
程序代码:
#include <stdio.h> #include <math.h> float f(float x) /*定义f函数,以实现f(x)=x*x*x-5*x*x+16*x-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) { y1 = y; x1 = x; } else { x2 = x; } } while (fabs(y) >= 0.0001); return (x); } void 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); }
[ 本帖最后由 firewater 于 2015-1-20 16:16 编辑 ]