/* root.c A simple iteration method for finding the zeroes of a quadratic function */ # include # include /* necessary for use of abs() */ double func(double x, double a, double b, double c); /* function prototype */ main() /* header for function main() */ { /* start of main() */ double x1, x2, x3, f, f1, f2, a, b, c, min; int step; printf("\nEnter values for a, b and c, separated by spaces or carriage returns:\n"); scanf("%lf %lf %lf", &a, &b, &c); printf("Enter a value of x for which f(x) is negative:\n"); scanf("%lf", &x1); while (func(x1, a, b, c) >=0) { printf("f(x) is not negative for this x. Choose another value:\n"); scanf("%lf", &x1); } printf("Enter a value of x for which f(x) is positive:\n"); scanf("%lf", &x2); while(func(x2, a, b, c) <=0) { printf("f(x) is not positive for this x. Choose another value:\n"); scanf("%lf", &x2); } step=1; min=0.001; do{ x3 = (x1 + x2)/2; f=func(x3, a, b, c); if (f>0){ x2=x3; } else { x1=x3; } step++; } while(fabs(f)>min); /* stops loop when f is sufficiently close to 0 */ printf("\nf(x) is zero at x=%0.2lf\n", x3); /* prints x to 2 places of decimals */ printf("Number of steps = %d\n", step); } /* end of main() */ double func(double x, double a, double b, double c) /* function header */ { /* start of func() */ double fvalue; fvalue = a*x*x + b*x + c; return fvalue; } /* end of func() */