home *** CD-ROM | disk | FTP | other *** search
/ C by Discovery (4th Edition) / C_By_Discovery_4th_Edition.tar / C_By_Discovery_4th_Edition / _DISK_ / ch11 / math.c < prev    next >
C/C++ Source or Header  |  2005-06-16  |  2KB  |  61 lines

  1. /*               math.c
  2.  *
  3.  *   Synopsis  - Accepts input of values for x and n and displays 
  4.  *               the calculated values from the pow(), sqrt() and 
  5.  *               tan() functions.
  6.  *
  7.  *   Objective - To illustrate error handling with the 
  8.  *               mathematical functions in the ANSI C library.
  9.  */
  10.  
  11. /* Include Files */
  12. #include <math.h>
  13. #include <stdio.h>
  14. #include <errno.h>                                             /* Note 1 */
  15. #include <stdlib.h>
  16.  
  17. /* Constant Definitions */
  18. #define BUF_SIZE  50
  19.  
  20. /* Function Declarations */
  21. void error( char *s );
  22. /*   PRECONDITION:  s contains the address of a string
  23.  *
  24.  *   POSTCONDITION: checks the value of errno, and if it is nonzero, 
  25.  *                  issues an error message
  26.  */
  27.  
  28. int main( void )
  29.      double n, x, y;
  30.      char buff[BUF_SIZE];
  31.  
  32.      printf( "Enter a value for n: " );
  33.      fgets( buff, BUF_SIZE, stdin );
  34.      n = strtod( buff, NULL );
  35.      printf( "Enter value for x: " );
  36.      fgets( buff, BUF_SIZE, stdin );
  37.      x = strtod( buff, NULL );
  38.      printf( "x is %5.2f.\n", x );
  39.      printf( "n is %5.2f.\n", n );
  40.      y = sqrt( x );                                            /* Note 2 */
  41.      error( "sqrt" );
  42.      printf( "sqrt(%4.2f) is %5.2f\n",x, y );                  /* Note 3 */
  43.      y = tan( x );                                             /* Note 4 */
  44.      error( "tan" );
  45.      printf( "tan(%4.2f) is %5.2f.\n", x, y );
  46.      y = pow( x, n );                                          /* Note 5 */
  47.      error( "pow" );
  48.      printf( "pow(%4.2f, %4.2f) is %5.2f.\n", x, n, y );
  49.      return 0;
  50. }
  51.  
  52. /*******************************error()*************************/
  53.  
  54. void error( char *s )
  55. {
  56.      if ( errno )                                              /* Note 6 */
  57.           perror( s );
  58.      errno = 0;                                                /* Note 7 */
  59. }
  60.