Intro CS I/fall2015/Function Fun

From Maryville College CS Wiki
< Intro CS I‎ | fall2015
Revision as of 09:31, 30 August 2016 by Robert.lowe (talk | contribs) (Robert.lowe moved page Intro CS I/Function Fun to Intro CS I/fall2015/Function Fun without leaving a redirect: semester changeover!)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

In this lecture we discussed functions. We then created a program using top-down design. This program performs many calculations about lines, and we used functions to keep the code simple and clean.

Almost all of this code was written in class by all of you!

#include <iostream>
#include <cmath>

using namespace std;
                //I apologize in advance


enum choice_type {ENDPOINTS = 1, COMPUTE_Y, COMPUTE_X, DISTANCE, EXIT};

//gets the user's menu choice
choice_type menu() {
  int choice;
  cout << "(1) enter end points." << endl;
  cout << "(2) compute y." << endl;
  cout << "(3) compute x." << endl;
  cout << "(4) distance." << endl;
  cout << "(5) exit." << endl;
  cin >> choice;
  return (choice_type) choice;
}
// Computes the slope of a line
double slope(double x1, double y1, double x2, double y2) {
  double m;

  //compute the slope
  m = (y2-y1) / (x2-x1);

  return m;
}


// Computes the Y-Intercept of a line
double intercept(double m, double x, double y) {
  double b = (y - (m*x));
  return b;
}


// Computes a Y from a given x
double computeY(double m, double b, double x) {
  double y = (m*x) + b;
  return y;
}

// Computes an x from a given y
double computeX(double m, double b, double y) {
  double x = (y-b)/m;
  return x;
}


// Compute a distance to the line
double distance(double m1, double b1,  double x1, double y1) {
        double b2;
        double x2;
        double y2;
        double m2;
        double d;

        m2 = -1 / m1;
        b2 = y1 + (1 / m1) * x1;
        x2 = (b2 -b1) / (m1 - m2);
        y2 = m2*x2 +b2;
        d = sqrt(pow(y2-y1,2) + pow(x2 -x1,2));

        return d;
}


int main() {
  double x1, y1;   //point 1
  double x2, y2;   //point 2
  double x, y;
  double m;
  double b;
  choice_type choice;

  //keep going until told otherwise
  do {
    choice = menu();
    switch(choice) {
    case ENDPOINTS:
      cout << "Point1: ";
      cin >> x1 >> y1;
      cout << "Point2: ";
      cin >> x2 >> y2;
      m = slope(x1, y1, x2, y2);
      b = intercept(m, x1, y1);
      break;

    case COMPUTE_Y:
      cout << "X: ";
      cin >> x;
      cout << "Y: " << computeY(m, b, x) << endl;
      break;

    case COMPUTE_X:
      cout << "Y: ";
      cin >> y;
      cout << "X: " << computeX(m, b, y) << endl;
      break;

    case DISTANCE:
      cout << "Point: ";
      cin >> x >> y;
      cout << distance(m, b, x, y) << endl;
      break;

    case EXIT:
      break;

    default:
      cout << "Invalid choice.  Please try again." << endl;
      break;
    }
  } while(choice != EXIT);

  return 0;
}