/* ---------------------------------------------------------------- ** Find the roots of a function f by either secant or bisection. ** Figure 23.6: The main module for the root-finder. ** Figure 23.7: The menu loop from main(). ** ---------------------------------------------------------------- */ #include "tools.h" #include "ffam.h" #include "root.h" /* Global external variable to control verbose output everywhere. */ bool verbose = true; /* Menu of program options. ------------------------------- */ static string menu[] = { "b find root using Bisection method", "s find root using Secant method", "n choose New parameters for function", "v", /* completed later according to state of verbose flag */ "q Quit" }; #define VMENU 3 /* position of "v" item in menu */ /* --------------------------------------------------------------- */ void main( void ) { char c; /* menu choice */ double root; /* value of root */ double x1, x2; /* starting interval or end points */ er_type return_code; /* result error code */ banner(); puts( "Root finder program" ); setup(); /* Get parameters for f(). */ do { /* update menu */ if (verbose) menu[VMENU] = "v turn off Verbose feedback"; else menu[VMENU] = "v turn on Verbose feedback"; /* display menu and get user selection */ c = menu_c( " Select next option:", 5, menu ); switch (c) { case 'b': printf( " Enter endpoints of search interval: " ); scanf( "%lg%lg", &x1, &x2 ); return_code = bisect( x1, x2, &root ); break; case 's': printf( " Enter two initial estimates for the root: " ); scanf( "%lg%lg", &x1, &x2 ); return_code = secant( x1, x2, &root ); break; case 'n': setup(); /* Read new parameters for function f(). */ continue; case 'v': verbose = !verbose; continue; case 'q': continue; default: cleanline( stdin ); continue; } if (return_code == ROOT_OK) printf( "\n The root is %g \n\n", root ); else printf( "\n Failed to find root--%s\n\n", errmsg[return_code] ); } while (c != 'q'); bye(); }