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

  1. /*                           slope.c
  2.  *
  3.  *   Synopsis  - The user enters the coordinates of two points
  4.  *               and the program will display the equation of
  5.  *               the line through those two points.
  6.  *
  7.  *   Objective - To illustrate the use of floating point types
  8.  *               in an applied program.
  9.  */
  10.  
  11. /* Include Files */
  12. #include <stdio.h>
  13.  
  14. /* Function Prototypes */
  15. void print_result( float x1, float y1, float x2, float y2);
  16. /* PRECONDITION:  x1, y1, x2, y2 can be any real numbers.
  17.  *
  18.  * POSTCONDITION: Calculates the slope and y-intercept of a 
  19.  *                line and displays the equation of the line.
  20.  */
  21.  
  22. int main( void )
  23. {
  24.      float x1, y1, x2, y2;                        /* The points */
  25.  
  26.  
  27.      /*  Input the coordinates of the points */
  28.      printf( "Enter the first point.\n" );
  29.      printf( "x: " );
  30.      scanf( "%f", &x1 );
  31.      printf( "y: " );
  32.      scanf( "%f", &y1 );
  33.  
  34.      printf( "Enter the second point.\n" );
  35.      printf( "x: " );
  36.      scanf( "%f", &x2 );
  37.      printf( "y: " );
  38.      scanf( "%f", &y2 );
  39.  
  40.      print_result( x1, y1, x2, y2 );
  41.      return 0;
  42. }
  43.  
  44. /*******************************print_result()******************/
  45.  
  46. void print_result( float x1, float y1, float x2, float y2 )
  47. {
  48.      float slope, y_int;
  49.  
  50.      /*  Check for a vertical line */
  51.      if ( x1 != x2 ) {
  52.           /* the line is not vertical, calculate
  53.            * the slope and y intercept
  54.            */
  55.  
  56.           slope = ( y2 - y1 ) / ( x2 - x1 );
  57.           y_int = y1 - slope * x1;
  58.  
  59.           /* Check for a horizontal line */
  60.           if ( slope == 0 )                  /* horizontal line */
  61.                printf( "The equation is y = %5.2f\n",y1 );
  62.           else {
  63.                printf( "The equation is " );
  64.                printf( "y = %5.2fx + %5.2f\n",slope, y_int );
  65.           }
  66.      }
  67.      else                                   /* vertical line */
  68.           printf( "The equation is x = %5.2f\n", x1 );
  69. }
  70.  
  71.