早教吧 育儿知识 作业答案 考试题库 百科 知识分享

一个关于弦截法求根的小问题,请大家帮忙看一下。x1,x2若输入相反数就可以出答案,其他数就没答案或者是错误的,怎么回事啊?应该怎么改呢?#include<stdio.h>#include<math.h>float

题目详情
一个关于弦截法求根的小问题,请大家帮忙看一下。x1,x2若输入相反数就可以出答案,其他数就没答案或者是错误的,怎么回事啊?应该怎么改呢? #include<stdio.h> #include<math.h> float f(float x) {float y; y=x*x*x-5*x*x+16*x-80; return(y); } float xpoint(float x1,float x2) {float x; x=f(x1)*(x1-x2)/(f(x2)-f(x1))+x1; return(x); } float root(float x1,float x2) {float x,flag; x=xpoint(x1,x2); flag=f(x); if(fabs(flag)==0) {return(x);} else root(x1=x,x2); } 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); }
▼优质解答
答案和解析
float root(float x1,float x2) { float x; x=xpoint(x1,x2); if(fabs(f(x))<=1e-6)return(x); else return root(x2,x); } int 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(0); x=root(x1,x2); printf("A root of equation is %8.4f\n",x); return 0; }