#include #include #include #include #define ERROR_BOUND 1e-10 double f[10]; int d; void readpoly ( int d ) { int i; for (i=0; i<=d; ++i) { f[i] = (double)(rand() % 11 - 5); if (i == d) while (f[i] == 0) f[i] = (double)(rand() % 11 - 5); printf("Coefficient of x^%d = %lf\n", i, f[i]); } printf("The input polynomial is:\n\tf(x) = "); for (i=d; i>=0; --i) printf("(%d)*x^%d%c", (int)f[i], i, (i)?'+':'\n'); } double evalpoly ( double x ) { double sum = 0, xpower = 1; int i; for (i=0; i<=d; ++i) { sum += f[i] * xpower; xpower *= x; } return sum; } double findroot ( double a, double b ) { double m, fm, fa, fb; fa = evalpoly(a); fb = evalpoly(b); while (fa * fb < 0) { m = (a + b) / 2; fm = evalpoly(m); if (fabs(fm) < ERROR_BOUND) return m; if (fa * fm < 0) { b = m; fb = fm; } else { a = m; fa = fm; } } printf("??? Invalid input detected in findroot()\n"); exit(2); } int main () { double fa, fb, root; int i; srand((unsigned int)time(NULL)); printf("Enter degree (2 <= d <= 9): "); scanf("%d", &d); if ((d < 2) || (d > 9)) d = 5; readpoly(d); fa = 0; for (i=0; i<=10; ++i) { fb = evalpoly((double)i); if (abs(fb) < ERROR_BOUND) { printf("+++ Integer root located: %d\n", i); exit(0); } if (fa * fb < 0) { root = findroot(i-1,i); printf("+++ Real root located: %14.12lf\n", root); exit(0); } fa = fb; } printf("!!! Failure to detect a root\n"); exit(1); }