/* --------------------------------------------------------------------- ** Figure 20.11: Selecting a function from a menu. ** --------------------------------------------------------------------- */ #include "tools.h" typedef double (*funcptr)( double ); double /* Base 2 logarithm */ log_2( double x ) { return log( x ) / log( 2 ); } void main( void ) { int choice; /* user's function selection index */ double x, fx; /* data input, calculated function value */ funcptr fp; /* function chosen by user */ #define CHOICES 7 string greeting = " Select a function:"; string names[CHOICES] = { "quit", "sine", "cosine", "tangent", "natural log", "base 2 log", "e to the x" }; funcptr function[CHOICES] = { NULL, sin, cos, tan, log, log_2, exp }; puts( " A Menu of Functions" ); for (;;) { choice = menu_i( greeting, CHOICES, names ); if (choice == 0) break; printf( " Enter x: " ); scanf( "%lg", &x ); fp = function[choice]; fx = fp(x); printf( "\n %s(%g) = %g \n", names[choice], x, fx ); } bye(); }