本文共 780 字,大约阅读时间需要 2 分钟。
/* 本实验用二分法求方程f(x) = x * x * x - 2 * x - 5 = 0在区间[2, 3]的根。*/#include#include double f(double x){ return x * x * x - 2 * x - 5;}int main(){ double a, b; double eps = 0.0001; //精度要求 printf("please input a b = "); //区间[a, b] scanf("%lf %lf", &a, &b); double x = (a + b) / 2.0; //x为区间中点 if(f(a) * f(b) < 0){ while(f(x) != 0){ x = (a + b) / 2; if(f(x) * f(a) < 0){ b = x; if(b - a < eps) break; } else{ a = x; if(b - a < eps) break; } } printf("\nthe root of f(x) = 0 is x = %f\n", (a + b) / 2.0); } else printf("\nno root! afresh input\n"); return 0;}
实验结果: