二分法求三次方程的根
二分法求根
#include "stdio.h" #define f(x) a*x*x*x+b*x*x+c*x+d int main() { freopen("in.txt", "r", stdin); int a, b, c, d; double x1, x2, x, y1, y2, y; while (scanf("%d%d%d%d", &a, &b, &c, &d) != EOF) { x1 = -100; x2 = 100; x = (x1+x2) / 2; while ((x2-x1) > 0.01) { y1 = f(x1); y2 = f(x2); y = f(x); if (y1 == 0) { x = x1; break; } if (y2 == 0) { x = x2; break; } if (y1*y < 0) { x2 = x; x = (x1+x2) / 2; } else { x1 = x; x = (x1+x2) / 2; } } printf("%.f\n", x); } return 0; }